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

Nik*_*wal 2 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();
            }
Run Code Online (Sandbox Code Playgroud)

Ang*_*ari 11

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

post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
Run Code Online (Sandbox Code Playgroud)

您也可以从这个答案中看到相同的讨论