HttpClient 解決中文亂碼

而遠之發表於2014-04-04
public static String httpGet(String url) {
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpClient client = new DefaultHttpClient();
            HttpResponse resp = client.execute(httpGet);
            
            HttpEntity entity = resp.getEntity();
            String respContent = EntityUtils.toString(entity , "GBK").trim();
            httpGet.abort();
            client.getConnectionManager().shutdown();

            return respContent;
            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

 

 

public static String httpPost(String url, Map<String, String> params){
  try {
       HttpPost httpPost
= new HttpPost(url); HttpClient client = new DefaultHttpClient(); List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(params.size()); for(Map.Entry<String, String> entry : params.entrySet()){ NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())); valuePairs.add(nameValuePair); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(valuePairs, "GBK"); httpPost.setEntity(formEntity); HttpResponse resp = client.execute(httpPost); HttpEntity entity = resp.getEntity(); String respContent = EntityUtils.toString(entity , "GBK").trim(); httpPost.abort(); client.getConnectionManager().shutdown(); return respContent; } catch (Exception e) { e.printStackTrace(); return null; } }

 

相關文章