如何使用Java Spring的RestTemplate的exchange方法将主体添加到HTTP请求?

时间:2018-08-22 00:53:27

标签: java spring http resttemplate

我正在尝试使用RestTemplate的last_adm方法发送HTTP请求。但是,由于某种原因,已发送请求的HTTP正文似乎为空。

这是我当前拥有的代码(原始代码更加复杂):

df

为了确认上面的代码是否有效,我在终端中运行了 id admidate disdate first_adm last_adm intervention fu_time 1 2010-01-01 2010-01-15 1 0 1 - 1 2011-01-01 2011-01-15 0 1 0 365 2 2010-02-01 2010-02-15 1 0 0 - 2 2011-01-01 2011-02-15 0 0 1 - 2 2012-01-01 2012-02-15 0 1 0 365 3 2010-01-01 2010-01-15 1 0 0 - 3 2010-03-01 2010-03-15 0 0 0 - 3 2011-03-01 2011-03-15 0 1 0 431 (侦听端口5678上的请求),并且在我的IDE中,我运行了上面的代码。我终端中的exchange命令打印出一个没有正文的HTTP请求(我希望它有一个带有字符串“ body contents”的正文)。

为什么这行不通?我该如何解决?

注意:这是让我决定使用package somepackage; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.web.client.RestTemplate; public class SomeMainClass { public static void main(String[] args) { HttpEntity<String> entity = new HttpEntity<>("body contents", new HttpHeaders()); new RestTemplate().exchange("http://localhost:5678/someRequest", HttpMethod.GET, entity, String.class); } } 方法的要求

  • 它必须是GET请求。
  • 请求中必须有一个正文。
  • 我必须设置一些标题。
  • 我需要阅读回复的正文。

1 个答案:

答案 0 :(得分:0)

InjectionToken方法没有正文。您可能需要将GET更改为HttpMethod.GET

如果要在HttpMethod.POST中提供参数,则可以将URL更改为GET之类的内容。 有关更多详细信息,请访问Spring RestTemplate GET with parameters