Harry
Harry

Reputation: 782

Sending a network request with a JSON header

So, I have a method that sends a request to a webserver and grabs a response and stores it into a string.

My problem is that it returns XML by default, but I wan it to return JSON. The guy working on the server side said "it defaults to XML, but you can send the request with a JSON header, and it'll return that."

So, my question is, what do I have to do to request JSON data coming back instead of XML? (By the way, the guy on the server side isn't available to answer this question)

Thanks for the help

public class NetworkRequest {
private List<NameValuePair> nameValuePairs;
private String URL;

public NetworkRequest(List<NameValuePair> nameValuePairs) {
    this.nameValuePairs = nameValuePairs;
}

public String sendRequest() {
    String result = "";
    InputStream isr = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(URL);

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }
    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                isr, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        isr.close();

        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error  converting result " + e.toString());
    }
    return result;
}

public void setURL(String URL) {
    this.URL = URL;
}
}

Upvotes: 0

Views: 47

Answers (1)

Vladimir
Vladimir

Reputation: 9753

You need to add appropriate Accept header to your HttpPost:

httppost.addHeader(new BasicHeader("Accept", "application/json"));

or simply

httppost.addHeader("Accept", "application/json");

Upvotes: 1

Related Questions