1. 程式人生 > >常用工具類(二):HttpUtil 傳送HTTP請求

常用工具類(二):HttpUtil 傳送HTTP請求

常用工具類(二):HttpUtil 傳送HTTP請求

public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    /**
     *
     * @param url 需要請求的地址
     * @param jsonParam 請求地址需要攜帶的引數
     * @return
     */
    public static String httpPost(String url, String jsonParam) {
        //RequestConfig 用於配置網路環境
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectTimeout(10000).build(); return httpPostExecute(url,jsonParam,requestConfig); } public static String httpPostExecute(String url, String jsonParam, RequestConfig requestConfig){ HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new
HttpPost(url); if (requestConfig != null) httpPost.setConfig(requestConfig); if (!StringUtils.isEmpty(jsonParam)){ //設定訊息體 StringEntity entity = new StringEntity(jsonParam, "utf-8"); entity.setContentEncoding("utf-8"); entity.setContentType("application/json"
); httpPost.setHeader("Accept-Encoding","gzip,deflate"); httpPost.setEntity(entity); } try { HttpResponse result = httpClient.execute(httpPost); //encode編碼 decode解碼 url = URLDecoder.decode(url,"utf-8"); if (result.getStatusLine().getStatusCode() == 200) { String str = ""; Header contentHeader = result.getFirstHeader("Content-Encoding"); if (contentHeader != null && contentHeader.getValue().toLowerCase().indexOf("gzip") > -1) { str = EntityUtils.toString(new GzipDecompressingEntity(result.getEntity()),"utf-8"); return str; } else { str = result.getEntity().toString(); return str; } } } catch (IOException e) { logger.info(url+"請求失敗",e); } return null; } public static String httpGet(String url) { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(50000).setConnectionRequestTimeout(10000).build(); return httpGetExecute(url,requestConfig); } public static String httpGetExecute(String url, RequestConfig requestConfig){ HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); if (requestConfig != null) httpGet.setConfig(requestConfig); httpGet.setHeader("Accept-Encoding", "gzip,default"); try { HttpResponse result = httpClient.execute(httpGet); String str = null; if (result.getStatusLine().getStatusCode() == 200) { Header contentHeader = result.getFirstHeader("Content-Encoding"); if (contentHeader != null && contentHeader.getValue().toLowerCase().indexOf("gzip") > -1) { str = EntityUtils.toString(new GzipDecompressingEntity(result.getEntity())); return str; } else { str = EntityUtils.toString(result.getEntity(),"utf-8"); return str; } } } catch (IOException e) { logger.info(url+"請求失敗",e); } return null; } }