apache http client post json 返回值 中文亂碼解決
阿新 • • 發佈:2019-01-07
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; } }