Apache HTTP请求在RESTful Web服务上以异常结束

时间:2016-04-16 16:40:05

标签: java spring web-services rest

我需要使用JUnit测试RESTful webservice *(使用spring)。我使用在测试工具中构建的IntelliJs测试了Web服务,它运行良好。所以现在我使用ApacheHttpClient在该webservice上执行POST请求。我启动RESTful Web服务,然后执行此代码

CloseableHttpClient httpclient = HttpClients.createDefault();
URI uri = new URIBuilder()
             .setScheme("http")
             .setHost("localhost")
             .setPort(8080)
             .setPath("/register")
             .build();
HttpPost post = new HttpPost(uri);
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("name", "test"));
nvps.add(new BasicNameValuePair("email", "test"));
nvps.add(new BasicNameValuePair("password", "test"));
post.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpclient.execute(post);
response.close();

但是这会以网络服务中的例外结束:

  

对URI http://localhost:8080/register的servlet请求包含请求主体中的表单参数,但请求主体已被servlet或访问请求参数的servlet过滤器使用。只有使用@FormParam的资源方法才能按预期工作。通过其他方式使用请求主体的资源方法将无法按预期工作。 UT005023:对/错误

的异常处理请求

完整的堆栈跟踪:http://pastebin.com/96aJtaS5

*完整源代码位于:https://github.com/pkalauner-tgm/dezsys09-java-webservices 谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

我需要通过

将请求的内容类型设置为json
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");