如何在apache httpPost方法中创建content-type:application / json

时间:2015-04-15 10:34:19

标签: java json content-type apache-httpclient-4.x

我正在使用下面的代码,它显示了Content-Type:application / x-www-form-urlencoded,但我希望这段代码是Content-Type:application / json。 请建议对此代码进行哪些更改以使其成为application / 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();
            }

3 个答案:

答案 0 :(得分:9)

在请求标题内设置内容类型....

post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");

您还可以在this answer

中看到相同的讨论

答案 1 :(得分:2)

这可能有需要..

response.setContentType("application/json");

答案 2 :(得分:0)

我认为取消注释

//post.setHeader("Content-type", "application/json");

将解决您的问题。