Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the content-type: application/json in the apache httpPost method [duplicate]

I am using the below code and it is showing the Content-Type:application/x-www-form-urlencoded, but I want this code to be Content-Type: application/json. Please suggest what changes needed to this code to make it an application/json request.

  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();
            }
like image 734
Nikunj Aggarwal Avatar asked Dec 02 '22 17:12

Nikunj Aggarwal


1 Answers

Set the content type inside header of the request....

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

you can also see the same discussion from this answer

like image 70
Angad Tiwari Avatar answered Dec 29 '22 16:12

Angad Tiwari