我有一个dropwizard服务,我实现了一个使用APPLICATION_FORM_URLENCODED媒体类型并使用@FormParam注释的帖子请求
然后在我的客户端我正在使用Apache HttpClient发出这样的帖子请求:
public void sendPost(String path, JsonObject params) throws Exception {
String url = "http://" + TS_API_HOST + ":" + TS_API_PORT + "/" + path;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Iterator<String> keys = params.keySet().iterator();
while(keys.hasNext()){
String currentKey = keys.next();
nvps.add(new BasicNameValuePair(currentKey, params.get(currentKey).toString()));
}
System.out.println(nvps.toString());
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
HttpEntity entity2 = response.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response.close();
}
}
我传递的url和params是正确的,但我仍然收到400个不良请求作为回复。
在邮递员中它运作良好......