4

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
  • 544
  • 2
  • 9
  • 24

3 Answers3

17

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
  • 22,898
  • 15
  • 55
  • 90
Angad Tiwari
  • 1,653
  • 1
  • 10
  • 22
0

I think uncommenting the line

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

will solve your problem.

Mansuro
  • 4,194
  • 4
  • 31
  • 72
Rahul
  • 299
  • 1
  • 10
-1

This may serve the need ..

response.setContentType("application/json");

Deepika Rajani
  • 568
  • 5
  • 14