Android中内容类型的JSON对象的HTTP POST请求问题

时间:2014-07-18 13:02:16

标签: android json http

以下是运行Android 4.1.2的Android设备中的HTTP POST请求的代码。我有疑问:

  • 此代码在三星设备上运行良好,而在HTC设备上提供“Content-type is not application / json”。

    public static String POST(String url,JSONObject obj) {     Log.i(“JSONPOSTBEGIN”,“JSON POST的开头”);     InputStream inputStream = null;     字符串结果=“”;

    HttpClient httpclient = new DefaultHttpClient();
    
    try {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "application/json");
        post.setHeader("Accept", "application/json");
    
        StringEntity se = new StringEntity(obj.toString()); 
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);
    
        HttpResponse httpResponse = mHhttpclient.execute(post);
    
        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();
    
        // convert inputstream to string
        if(inputStream != null) {
            result = convertInputStreamToString(inputStream);
        } else
            result = "Did not work!";
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
    Log.i("JSONPOSTEND", "End of JSON data post methos...");
    return result;
    

    }

2 个答案:

答案 0 :(得分:0)

要使其适用于HTC和所有设备,您必须执行此操作

private static HttpEntity getHttpEntity(String stringEntity) {
    HttpEntity entity = null;
    try {
        entity = new StringEntity(stringEntity, HTTP.UTF_8);
        ((StringEntity) entity).setContentType("application/json;charset=UTF-8");
        ((StringEntity) entity).setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));

    } catch (Exception e) {
        Log.d("error creating entity: " + stringEntity);
    }
    return entity;
}

答案 1 :(得分:0)

请注意,标题可能是由此

设置的

新的HttpPost(网址);

并且在添加“内容类型”之类的新标题之前,您可能必须首先调用删除标题(Content-type)....

你需要记录才能把它全部弄清楚。有关详细信息,请参阅接受的ans here

并获得WIRE& HEADER在您的测试环境中登录