我正在使用apache httpClient post方法来调用rest客户端API,但API提供了错误的响应,因此我想调试该方法并希望以json格式打印请求。 下面是我正在使用的代码 -
private String baseUrl = "myIPAddress";
private HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(baseUrl + "app/registration");
try {
String line = "";
for (int rIndex = 0; rIndex < goodAuthenticationPairs.length; rIndex++) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("email","myEmail@test.com"));
nameValuePairs.add(new BasicNameValuePair("password","myPassword"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//post.setHeader("Content-type", "application/json");
System.out.println(post);
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
line = rd.readLine();
System.out.println(line);
JSONObject json = (JSONObject) new JSONParser().parse(line);
String actualResult = json.get("return_code").toString();
assertTrue("0".equals(actualResult));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
答案 0 :(得分:0)
我得到了答案。 上面的代码是在Content-Type中发送请求:application / x-www-form-urlencoded但服务器API需要Content-Type:application / json