6

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","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();
            }
Nikunj Aggarwal
  • 754
  • 2
  • 12
  • 32

3 Answers3

21

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

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Angad Tiwari
  • 1,738
  • 1
  • 12
  • 23
0

I think uncommenting the line

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

will solve your problem.

Mansuro
  • 4,558
  • 4
  • 36
  • 76
Rahul
  • 309
  • 1
  • 11
-2

This may serve the need ..

response.setContentType("application/json");

Deepika Rajani
  • 564
  • 5
  • 15