apache http client post json中文乱码解决

手册/FAQ (462) 2016-04-14 13:51:34

import org.apache.commons.httpclient.HttpException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.json.JSONTokener;

public class HttpPostClient {

public static JSONObject postMethod(String url,String jsonString) {

DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(jsonString, "UTF-8");   // 中文乱码在此解决
s.setContentType("application/json");
post.setEntity(s);

HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
String charset = EntityUtils.getContentCharSet(entity);
response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(), charset)));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;

}

}

THE END