HttpClient基礎用法

1、HttpClientapache

    HttpClient是Apache HttpComponents 下的子項目,用來提供高效的、最新的、功能豐富的支持HTTP協議的客戶端編程工具包(httpclient-4.4.1.jar)。HttpClient類能夠用來發送Http請求(get,post,put,delete)相比傳統JDK自帶的URLConnection,增長了易用性和靈活性,以下爲一個post類型的HTTP請求,參數列表中的header表明HTTP請求的header,params表明參數列表,body表明HTTP請求體編程

須要導入:import org.apache.http.client.HttpClients等
    public String post(String url,Map<String, String> header, Map<String, Object> params, Map<String, Object> entity, int soTimeout) {
        CloseableHttpClient httpclient = HttpClients.createDefault();  //建立一個httpclient
        HttpPost httppost = new HttpPost();  //建立一個httppost
        String result = null;
        try {
            //處理params,拼接url
            url = joinParam(url, params);  //根據需求本身實現該方法 //add request url
            if (url != null) {
                httppost.setURI(URI.create(url));
            }

            //add header
            for (String key : header.keySet()) {
                httppost.addHeader(key, header.get(key));
            }

            //add entity
            if (entity != null) {
                String entityStr = toJSONString(entity);  //將map轉化爲string
                StringEntity stringEntity = new StringEntity(entityStr, "UTF-8");
                stringEntity.setContentType("text/json");
                stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                httppost.setEntity(stringEntity);
            }
            /**
             * setConnectTimeout:設置鏈接超時時間,單位毫秒。
             *setConnectionRequestTimeout:設置從connect Manager獲取Connection 超時時間,單位毫秒。這個屬性是新加的屬性,由於目前版本是能夠共享鏈接池的。
             *setSocketTimeout:請求獲取數據的超時時間,單位毫秒。
             */
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(soTimeout).setConnectionRequestTimeout(soTimeout)
                    .setSocketTimeout(soTimeout).build();
            httppost.setConfig(requestConfig);

            CloseableHttpResponse response = null;
            try {
//發送post請求 response
= httpclient.execute(httppost); } catch (IOException e) { e.printStackTrace(); }
try { // 獲取響post響應實體 if (response != null) { HttpEntity responseEntity = response.getEntity(); if(responseEntity != null) { result = responseEntity.toString(); if(responseEntity != null) { result = EntityUtils.toString(responseEntity); } } } } finally { if (response != null) { response.close(); } } } catch (Exception e) { e.printStackTrace(); } finally { // 關閉鏈接,釋放資源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }

 

 2、老版本HttpClient(commons-httpclient.jar)json

    進入apache官網下找commons HttpClient包,能夠看到一下描述:app

The Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules, which offer better performance and more flexibility.工具

    能夠看到commons-httpclient.jar已被httpclient.jar取代,官方再也不提供commons-httpclient的更新維護服務。如下是使用老版本HttpClient發送一個post請求:post

    須要導入:import org.apache.commons.httpclient.HttpClient等flex

    public String doPost(String url, Map<String, String> header, Map<String, Object> entity){
        String result = "";
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        try{
            //set header
            postMethod.addRequestHeader("Content-Type", "application/json");
            for (String key : header.keySet()) {
                postMethod.addRequestHeader(key, header.get(key));
            }

            //set entity
            String paramsStr = toJSONString(entity);
            RequestEntity requestEntity = new ByteArrayRequestEntity(paramsStr.getBytes("UTF-8"));
            postMethod.setRequestEntity(requestEntity);

            //get response
            int httpStatusCode = httpClient.executeMethod(postMethod);
            if (httpStatusCode < 200 || httpStatusCode >= 300) {
                throw new Exception("httpStatusCode is not correct! " + httpStatusCode);
            }
            result = IOUtils.toString(postMethod.getResponseBodyAsStream(), "UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            postMethod.releaseConnection();
        }
        return result;
    }
相關文章
相關標籤/搜索