我在下面的代码中使用RestTemplate发出GET请求。如果我直接从chrome / postman调用该请求,则该请求正常。但是,它不能从代码中工作。似乎忽略了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
的完整跟踪
感谢您的帮助。预先感谢。
编辑-是否可以通过在发出请求的restTemplate中检查/打印URL的方法?
答案 0 :(得分:1)
您会错过一件事,如果您查看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()
}
}