首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >TestRestTemplate.postForEntity返回400,没有描述性消息

TestRestTemplate.postForEntity返回400,没有描述性消息
EN

Stack Overflow用户
提问于 2018-06-13 07:21:38
回答 1查看 447关注 0票数 1

我在使用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()));
}

我注意到在TestRestTemplate的Javadoc中写道:

如果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“更多的信息?我真的很感激。

EN

回答 1

Stack Overflow用户

发布于 2018-06-13 07:47:27

经过一番搜索,我发现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()); 
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50827143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档