我在下面的代码中使用RestTemplate做一个GET请求。如果我直接从chromepostman调用它,请求可以正常工作。但是,从代码中看,它却不能正常工作。它似乎忽略了rootUri。
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
@Component
class Provider(
private val builder: RestTemplateBuilder
) {
var client: RestTemplate = builder.rootUri("http://foo.test.com/API/rest").build()
fun sendMessage(request: Request) {
println("here is the request")
try {
val resp = client.getForEntity(
"?userid=123456&password=1234356&method=TEST_MESSAGE", Response::class.java
)
} catch (e: Exception) {
println("this is the error")
e.printStackTrace()
}
}
}
这是我得到的异常。
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "": null; nested exception is org.apache.http.client.ClientProtocolException
....
....
Caused by: org.apache.http.client.ClientProtocolException
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:187)
Caused by: org.apache.http.client.ClientProtocolException
....
....
Caused by: org.apache.http.ProtocolException: Target host is not specified
at org.apache.http.impl.conn.DefaultRoutePlanner.determineRoute(DefaultRoutePlanner.java:71)
at org.apache.http.impl.client.InternalHttpClient.determineRoute(InternalHttpClient.java:125)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
Caused by: org.apache.http.ProtocolException: Target host is not specified
完整的跟踪在 http:/collabedit.comt6h2f
任何帮助都是感激的。先谢谢你。
编辑--有什么方法可以从restTemplate中检查出get请求的url?
你错过了一件事,如果你看看RestTemplateBuilder.rootUri(...)文档,他们将rootUri设置为任何请求的开头。/
.但如果你没有添加它,它将忽略rootUri值。
因此,如果你只修改你的调用,它就会工作。
val resp = client.getForEntity(
"/?userid=123456&password=1234356&method=TEST_MESSAGE", Response::class.java
)
更新。
var client: RestTemplate = builder.rootUri("http://foo.test.com/").build()
fun sendMessage(request: Request) {
println("here is the request")
try {
val resp = client.getForEntity(
"/API/rest?userid=123456&password=1234356&method=TEST_MESSAGE", Response::class.java
)
} catch (e: Exception) {
println("this is the error")
e.printStackTrace()
}
}