1. 程式人生 > >使用HttpURLConnection,請求結果亂碼。

使用HttpURLConnection,請求結果亂碼。

在使用網上一些HttpUtils,請求返回後,有中文,讀取時發生亂碼,使用
HttpClients
,以下是解決方法。


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.google.common.collect.Lists;

/**
 * Created by lihengjie on 2016/11/27.
 */
public class HttpClentT {

    public static String send(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        InputStream is = null;
        //封裝請求引數
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("cityEname", "henan"));
        String str = "";
        String result = "";
        try {
            //轉換為鍵值對
            str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
            System.out.println(str);
            //建立Get請求
            HttpGet httpGet = new HttpGet(url + "?" + str);
            //執行Get請求,
            response = httpClient.execute(httpGet);
            //得到響應體
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                is = entity.getContent();
                //轉換為位元組輸入流
                BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
                String body = null;
                while ((body = br.readLine()) != null) {
                    result = body;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //關閉輸入流,釋放資源
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //消耗實體內容
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //關閉相應 丟棄http連線
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    }
}