【问题标题】:Cannot send a GET request with RESTTemplate无法使用 RESTTemplate 发送 GET 请求
【发布时间】:2015-06-13 09:56:41
【问题描述】:

我需要发送如下请求

 http://server.com/server1/index.php?id=123&name=jack&date=12.1.2016

我正在使用以下代码,但它似乎没有发送正确的请求,因为响应对象为空。我也想知道如何显示 restTemplate 发送的完整 url?我知道可以使用 WireShark,但有什么方法可以使用 restTemplate 检索它吗?

代码

String url = "http://server.com/server1/index.php?"
Map<String,String> vars = new HashMap<String,String>();
vars.put("id","123");
vars.put("name","jack");
vars.put("date","12.1.2016");

Profile profile = restTemplate.getForObject(url,Profile.class,vars);

【问题讨论】:

    标签: java spring resttemplate


    【解决方案1】:

    您可以将org.springframework.web.client.RestTemplate 的日志级别设置为调试,然后您将获得类似于此的输出:

    12:11:22.072 [main] 调试 o.s.web.client.RestTemplate - 为“http://echo.jsontest.com/key/value/one/two”创建 GET 请求
    12:11:22.110 [main] 调试 o.s.web.client.RestTemplate - 将请求接受标头设置为 [application/json, application/*+json]
    12:11:24.492 [main] DEBUG o.s.web.client.RestTemplate - 对“http://echo.jsontest.com/key/value/one/two”的 GET 请求导致 200(OK)
    12:11:24.494 [main] DEBUG os.web.client.RestTemplate - 使用 [org.springframework.http.converter] 将 [class com.example.TestOptional$Echo] 读取为“application/json;charset=ISO-8859-1” .json.MappingJackson2HttpMessageConverter@16f7c8c1]

    在那里您可以看到请求 URL 和返回的 HTTP 状态代码。

    如果你使用的是 Logback xml 配置 你会写

    <logger name="org.springframework.web.client.RestTemplate" level="DEBUG" />
    

    【讨论】:

      【解决方案2】:

      此 URL 模板中没有模板变量:

      String url = "http://server.com/server1/index.php?";
      

      我认为您需要像这样明确指定它们:

      String url = "http://server.com/server1/index.php?id={id}&name={name}&date={date}";
      

      在此模板中,id 是查询字符串参数的名称,{id} 指的是您的 vars 映射中的一个键。

      除了按照 andih 的描述打开日志记录之外,您还可以使用一组给定的变量来实例化 URL 模板,如下所示:

      new UriTemplate(url).expand(vars).toString()
      

      【讨论】:

      • 感谢您的回答,请您详细说明日志记录解决方案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多