1. 程式人生 > >httpClient包實現帶hreader和引數的get請求內容為json格式的post請求

httpClient包實現帶hreader和引數的get請求內容為json格式的post請求

直接上程式碼,專案時maven專案,需要在pom檔案中匯入程式碼中需要引用的jar包;

 

package com.jokin.learn.HttpTools;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import org.apache.http.*;
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.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

public class HttpUtil {

    private Log logger = LogFactory.getLog(this.getClass());
    private static final String pattern = "yyyy-MM-dd HH:mm:ss:SSS";

    /**
     *實現get請求
     * @param baseUrl
     * @param parameters    傳入引數的map;當無引數時,傳入的map=null即可
     * @param headers    傳入header的map, 例如cookies等,當無值時,傳入null即可
     * @return
     */
    public String get1(String baseUrl,Map<String, String> parameters ,Map<String, String> headers ){
        //建立一個httpclient物件
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //建立一個返回值物件
        CloseableHttpResponse response = null;
        String entityString=null;
        try {
            URIBuilder uriBuilder = new URIBuilder(baseUrl);
            if(parameters!=null&&parameters.size()>0){
                for (Map.Entry<String, String> temp : parameters.entrySet() ) {
                    //迴圈map裡面的每一對鍵值對,然後獲取key和value即時想要的引數的 key和value
                    uriBuilder.addParameter(temp.getKey(),temp.getValue());
                }
            }
            /*URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
            uriBuilder.addParameter("query", "花千骨");*/
            HttpGet get = new HttpGet(uriBuilder.build());//生產一個httpget連線
            //新增head, 用setheader 如果已經存在就重置, addheader如果已經存在進行新增同名的header
            if(headers!=null&&headers.size()>0){
                for (Map.Entry<String, String> temp : headers.entrySet() ) {
                    //迴圈map裡面的每一對鍵值對,然後獲取key和value即時想要的引數的 key和value
                    get.setHeader(temp.getKey(),temp.getValue());
                }
            }
            //執行請求
            response = httpClient.execute(get);
            //取響應的結果
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            HttpEntity entity = response.getEntity();
            entityString = EntityUtils.toString(entity, "utf-8");
            System.out.println(entityString);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(response !=null){
                    response.close();
                }
                if (httpClient!=null){
                    httpClient.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return entityString;

    }


    /**
     * 傳入的引數為Json格式的的post請求實現方式
     * @param baseUrl
     * @param parameters
     * @return
     */
    public String post(String baseUrl,String parameters) {
        //CloseableHttpClient 實現了HttpClient, Closeable兩個介面
        CloseableHttpClient  httpClient = HttpClients.createDefault();
        HttpPost postmethod = new HttpPost(baseUrl);
        //建立一個uri物件
        CloseableHttpResponse response = null;
        long startTime = 0L;
        long endTime = 0L;
        int status = 0;
        String bodyString = null;
        logger.info("parameters:" + parameters);

        if (postmethod != null ) {
            try {

                // 建立一個NameValuePair陣列,用於儲存欲傳送的引數
                postmethod.addHeader("Content-type","application/json; charset=utf-8");
                postmethod.setHeader("Accept", "application/json");
                if(parameters != null && !"".equals(parameters.trim())){
                    postmethod.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
                }
                startTime = System.currentTimeMillis();
                response = httpClient.execute(postmethod);

                endTime = System.currentTimeMillis();
                int statusCode = response.getStatusLine().getStatusCode();

                logger.info("statusCode:" + statusCode);
                logger.info("呼叫API 花費時間(單位:毫秒):" + (endTime - startTime));
                if (statusCode != HttpStatus.SC_OK) {
                    logger.error("Method failed:" + response.getStatusLine());
                    status = 1;
                }

                // Read the response body
                bodyString = EntityUtils.toString(response.getEntity());

            } catch (IOException e) {
                // 網路錯誤
                status = 3;
            } finally {
                logger.info("呼叫介面狀態:" + status);
                try {
                    if(response !=null){
                        response.close();
                    }
                    if (httpClient!=null){
                        httpClient.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return bodyString;
    }



    /**
     * get帶參呼叫方式二
     * @param url
     * @param parametersList
     * @return
     */
    public String get2(String url ,List<NameValuePair> parametersList) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        InputStream is = null;
        String entityString =null;
        String baseUrl =url;
        //String baseUrl = "http://localhost:8080/MyWebxTest/getCityByProvinceEname.do";
        /*//封裝請求引數
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("cityEname", "henan"));*/
        String str = "";
        try {
            //轉換為鍵值對
            str = EntityUtils.toString(new UrlEncodedFormEntity(parametersList, Consts.UTF_8));
            System.out.println(str);
            //建立Get請求
            HttpGet httpGet = new HttpGet(baseUrl+"?"+str);
            //執行Get請求,
            response = httpClient.execute(httpGet);
            //得到響應體
            HttpEntity entity= response.getEntity();
            entityString = EntityUtils.toString(entity);
            if(entity != null){
                is = entity.getContent();
                //轉換為位元組輸入流
                BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
                String body = null;
                while((body=br.readLine()) != null){
                    System.out.println(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  entityString;


    }


}