[英]How to send post request with content-type x-www-form-urlencoded android retrofit
[英]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.