2015-04-15 46 views
0

我正在使用apache httpClient post方法來調用rest客戶端API,但是API提供的響應不正確,所以我想調試該方法並希望以json格式打印請求。 下面是我正在使用的代碼 -如何以json格式打印httpPost請求?

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","[email protected]")); 
        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

我得到了答案。 上面的代碼是在Content-Type中發送請求:application/x-www-form-urlencoded,但服務器API期望Content-Type:application/json