使用JSON标头发送网络请求

时间:2014-10-15 15:01:27

标签: android xml json

所以,我有一个方法可以向Web服务器发送请求并获取响应并将其存储到字符串中。

我的问题是它默认返回XML,但我想它返回JSON。在服务器端工作的人说“它默认为XML,但你可以用JSON头发送请求,它将返回它。”

所以,我的问题是,我需要做什么来请求JSON数据而不是XML? (顺便说一句,服务器端的人无法回答这个问题)

感谢您的帮助

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;
}
}

1 个答案:

答案 0 :(得分:1)

您需要为HttpPost添加适当的Accept标头:

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

或只是

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