繁体   English   中英

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

[英]Problems with HTTP POST request for JSON object for content-type in Android

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

  • 该代码在Samsung设备上完美运行,而在HTC设备上给出“ Content-type not application / json”。

    公共静态字符串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; 

    }

为了使其能够在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;
}

请注意,标题可能是由此设置的

新的HttpPost(url);

在添加新的标题(如“ content-type”)之前,您可能必须先调用remove header(Content-type)。

您需要记录以解决所有问题。有关更多信息,请参见此处接受的答案。

并在测试环境中记录WIRE&HEADER

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM