我在使用TestRestTemplate.postForEntity()时遇到了一些麻烦。我的代码是:
@Test
public void testAdd() {
Map<String,String> mParams=new HashMap<>();
mParams.put("joke","This is my joke");
mParams.put("description","Totally Tasteless Joke");
mParams.put("date",Long.toString(System.currentTimeMillis()));
ResponseEntity<Joke> reJoke = restTemplate.postForEntity(getURLBase()+"/add",
null,
Joke.class,
mParams
);
Joke j = reJoke.getBody();
System.out.println("Status="+reJoke.getStatusCode()+" j.getJoke()="+j.getJoke()+" id="+j.getId());
}
返回的状态值为400.控制台上没有打印任何内容。
我有一个可行的testGet():
@Test
public void testGet() {
System.out.println("testGet()");
initData();
ResponseEntity<Joke> reJoke=restTemplate.getForEntity(getURLBase()+"/1",Joke.class,new HashMap<String,String>());
Joke j=reJoke.getBody();
System.out.println("Status=" + reJoke.getStatusCode()+" j =" + j + (j == null ? "" : j.getJoke()));
}
我在Javadoc中注意到TestRestTemplate它说:
如果Apache Http Client 4.3.2或更高版本可用(推荐),它将用作客户端,默认情况下配置为忽略cookie和重定向。
我添加了
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
<scope>test</scope>
</dependency>
到pom.xml,但它似乎没有任何区别。
有谁能告诉我如何解决问题,或者获得比“400”更多的信息?真的很感激。
答案 0 :(得分:0)
经过一番搜索,我发现mParams实际上是URL参数。我需要将表单编码参数作为请求对象发送。工作代码是:
@Test
public void testAdd() {
MultiValueMap<String, String> mParams= new LinkedMultiValueMap<String, String>();
mParams.add("joke", "This is my joke");
mParams.add("description", "Totally Tasteless Joke");
mParams.add("date", Long.toString(System.currentTimeMillis()));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(mParams, headers);
ResponseEntity<Joke> reJoke = restTemplate.postForEntity(getURLBase()+"/add",
request,
Joke.class
);
Joke j = reJoke.getBody();
System.out.println("Status="+reJoke.getStatusCode()+" j.getJoke()="+j.getJoke()+" id="+j.getId());
}