[英]Problems with HTTP POST request for JSON object for content-type in Android
The following is my code for a HTTP POST request in an Android device running Android 4.1.2. 以下是我针对运行Android 4.1.2的Android设备中的HTTP POST请求的代码。 I have question:
我有问题:
This code works perfectly on a Samsung device whereas it is giving "Content-type is not application/json" on an HTC device. 该代码在Samsung设备上完美运行,而在HTC设备上给出“ Content-type not application / json”。
public static String POST(String url, JSONObject obj) { Log.i("JSONPOSTBEGIN", "Beginning of JSON POST"); 公共静态字符串POST(String url,JSONObject obj){Log.i(“ JSONPOSTBEGIN”,“ JSON POST的开始”); InputStream inputStream = null;
InputStream inputStream = null; String result = "";
字符串结果=“”;
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;
} }
For it to work on HTC and all devices, you must do this 为了使其能够在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;
}
Note that headers are likely being set by this 请注意,标题可能是由此设置的
new HttpPost(url); 新的HttpPost(url);
and that before you add new headers like for "content-type" you may have to call remove header (Content-type) first.... 在添加新的标题(如“ content-type”)之前,您可能必须先调用remove header(Content-type)。
you need logging to figure it all out.for more on that see accepted ans here 您需要记录以解决所有问题。有关更多信息,请参见此处接受的答案。
and get WIRE & HEADER logging up in your test environment 并在测试环境中记录WIRE&HEADER
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.