介面自動化測試框架--http請求的get、post方法的實現

weixin_30924079發表於2020-04-04

已知兩種方法。一種是通過httpclient實現(貌似很簡單,以後看一下),一種是以下方法:

Client實現:

package common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by zipon on 2018/8/27.
 */
public class HttpClientUtil {
    Logger log = new LogUtil("http_log").logger;
    /**
     * Post方式 得到JSONObject
     *
     * @param params post引數
     * @param url
     * @encoding 編碼格式,這裡直接寫死為utf-8
     * @return
     */
    public JSONObject doPost(JSONObject params, String url) throws IOException {
        //建立httpClient連線
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;

        JSONObject resultJsonObject = new JSONObject();
        try {
            StringEntity entity = new StringEntity(params.toString(),"utf-8");
            HttpPost httpPost = new HttpPost(url);
            //httpPost.addHeader("Content-Type","application/json");
            // 為HttpPost設定實體資料
            httpPost.setEntity(entity);
            log.info("******************請求開始********************");
            log.info(String.format("請求url資訊:%s",httpPost.getRequestLine()));
            log.info("請求headers資訊:");
            String headerList ="";
            for (Header header :httpPost.getAllHeaders()){
                headerList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info(headerList);
            log.info("請求body:");
            log.info(httpEntityToJSONObject(httpPost.getEntity()));
            // HttpClient 傳送Post請求
            httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // CloseableHttpResponse
                HttpEntity httpEntity = httpResponse.getEntity();
                resultJsonObject = httpEntityToJSONObject(httpEntity);
            }else{
                resultJsonObject.put("errorMessage",httpResponse);
            }
            log.info("返回headers資訊:");
            log.info(httpResponse.getAllHeaders());
            log.info("返回body:");
            log.info(httpResponse.getEntity());
            log.info("******************請求結束********************");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            httpResponse.close();
            httpClient.close();
        }
        return resultJsonObject;
    }

    /**
     * 沒有headers 沒有cookie插入的快速post
     * @param params
     * @param url
     * @return
     * @throws IOException
     */
//    public BaseResponse doPost(JSONObject params, String url) throws IOException {
//        //建立httpClient連線
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        CloseableHttpResponse httpResponse = null;
//
//        BaseResponse baseResponse = new BaseResponse();
//        try {
//            StringEntity entity = new StringEntity(params.toString(),"utf-8");
//            HttpPost httpPost = new HttpPost(url);
//            // 為HttpPost設定實體資料
//            httpPost.setEntity(entity);
////            預設Content-Type
//            httpPost.addHeader("Content-Type","application/json");
//            System.out.println(httpEntityToJSONObject(httpPost.getEntity()));
//            // HttpClient 傳送Post請求
//            httpResponse = httpClient.execute(httpPost);
//            baseResponse = httpResponseToBaseResponse(httpResponse);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            httpResponse.close();
//            httpClient.close();
//        }
//        return baseResponse;
//    }

    /**
     * 主用這個
     * @param params
     * @param url
     * @param headers
     * @param cookie
     * @return
     * @throws IOException
     */
    public BaseResponse doPost(JSONObject params, String url ,JSONObject headers ,String cookie) throws IOException {
        //建立httpClient連線
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;

        BaseResponse baseResponse = new BaseResponse();
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity;
            if (headers.get("Content-Type")=="application/x-www-form-urlencoded") {
                List<NameValuePair> pairs = new ArrayList<>(32);
                for (String key : params.keySet()) {
                    pairs.add(new BasicNameValuePair(key,params.get(key).toString()));
                }
                log.info(pairs);
                entity = new UrlEncodedFormEntity(pairs,"utf-8");
            }
            else {
                entity = new StringEntity(params.toString(), "utf-8");
            }
            addHeaders(httpPost,headers);
            addCookies(httpPost,cookie);
            log.info("******************請求開始********************");
            log.info(String.format("請求url資訊:%s",httpPost.getRequestLine()));
            String headerList ="";
            for (Header header :httpPost.getAllHeaders()){
                headerList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info("請求headers資訊:\r\n"+headerList.substring(0,headerList.length()-2));
//            httpPost.addHeader("Content-Type","application/json");
            // 為HttpPost設定實體資料
            httpPost.setEntity(entity);
            log.info("請求body:\n"+httpEntityToJSONObject(httpPost.getEntity()));
//            log.info(httpEntityToJSONObject(httpPost.getEntity()));
            // HttpClient 傳送Post請求
            httpResponse = httpClient.execute(httpPost);
            baseResponse = httpResponseToBaseResponse(httpResponse);
            String repheaderList ="";
            for (Header header :httpResponse.getAllHeaders()){
                repheaderList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info("返回headers資訊: \r\n"+repheaderList.substring(0,repheaderList.length()-2));
            log.info("返回body:\n"+baseResponse.getResponseBody());
//            log.info(baseResponse.getResponseBody());
            log.info("******************請求結束********************");

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            httpResponse.close();
            httpClient.close();
        }
        return baseResponse;
    }



//
//    public JSONObject getJSONObjectByGet(String url) throws IOException {
//        JSONObject resultJsonObject=null;
//
//        //建立httpClient連線
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        // HttpClient 傳送Post請求
//        CloseableHttpResponse httpResponse = null;
//        try{
//            StringBuilder urlStringBuilder=new StringBuilder(url);
//            //利用URL生成一個HttpGet請求
//            HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
////            httpGet.setHeader("Content-Type","text/123");
//            System.out.println(httpGet.getMethod());
//            for (Header header :httpGet.getAllHeaders()){
//                String key = header.getName();
//                String value = header.getValue();
//                System.out.println(String.format("%s:%s",key,value));
//            }
//            System.out.println(httpGet.getProtocolVersion());
//            System.out.println(httpGet.getRequestLine());
//
//            httpResponse=httpClient.execute(httpGet);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally{
//            httpResponse.close();
//            httpClient.close();
//        }
//        //得到httpResponse的狀態響應碼
//        if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK) {
//            //得到httpResponse的實體資料
//            HttpEntity httpEntity=httpResponse.getEntity();
//            resultJsonObject = httpEntityToJSONObject(httpEntity);
//        }
//        return resultJsonObject;
//    }

    /**
     * 不帶headers、cookies引數的get請求
     * @param url
     * @return
     * @throws IOException
     */
    public BaseResponse doGet(String url) throws IOException  {
        //建立httpClient連線
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // HttpClient 傳送get請求
        CloseableHttpResponse httpResponse = null;
        BaseResponse baseResponse = new BaseResponse();
        try{
            StringBuilder urlStringBuilder=new StringBuilder(url);
            //利用URL生成一個HttpGet請求
            HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
            log.info("******************請求開始********************");
            log.info(String.format("請求url資訊:%s",httpGet.getRequestLine()));
            String headerList ="";
            for (Header header :httpGet.getAllHeaders()){
                headerList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info("請求headers資訊:\r\n"+headerList.substring(0,headerList.length()-2));
            httpResponse=httpClient.execute(httpGet);
            baseResponse = httpResponseToBaseResponse(httpResponse);
            String repheaderList ="";
            for (Header header :httpResponse.getAllHeaders()){
                repheaderList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info("返回headers資訊: \r\n"+repheaderList.substring(0,repheaderList.length()-2));
            log.info("返回body:");
            log.info(baseResponse.getResponseBody());
            log.info("******************請求結束********************");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            httpResponse.close();
            httpClient.close();
        }
        return baseResponse;
    }

    public BaseResponse doGet(String url,JSONObject headers,String cookies) throws IOException {
        //建立httpClient連線
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // HttpClient 傳送get請求
        CloseableHttpResponse httpResponse = null;
        BaseResponse baseResponse = new BaseResponse();
        try{
            StringBuilder urlStringBuilder=new StringBuilder(url);
            //利用URL生成一個HttpGet請求
            HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
            addHeaders(httpGet,headers);
            addCookies(httpGet,cookies);
            log.info("******************請求開始********************");
            log.info(String.format("請求url資訊:%s",httpGet.getRequestLine()));
            String headerList ="";
            for (Header header :httpGet.getAllHeaders()){
                headerList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info("請求headers資訊:\r\n"+headerList.substring(0,headerList.length()-2));
            httpResponse=httpClient.execute(httpGet);
            baseResponse = httpResponseToBaseResponse(httpResponse);
            String repheaderList ="";
            for (Header header :httpResponse.getAllHeaders()){
                repheaderList += header.getName()+":"+header.getValue()+"\r\n";
            }
            log.info("返回headers資訊: \r\n"+repheaderList.substring(0,repheaderList.length()-2));
            log.info("返回body:");
            log.info(baseResponse.getResponseBody());
            log.info("******************請求結束********************");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            httpResponse.close();
            httpClient.close();
        }
        return baseResponse;
    }

    /**
     * 將HttpEntity類轉換為JSONObject封裝方法,表單鍵值對格式直接put到formData裡去
     * @param httpEntity
     * @return
     */
    public JSONObject httpEntityToJSONObject(HttpEntity httpEntity){
        StringBuilder entityStringBuilder=new StringBuilder();
        JSONObject resultJsonObject=new JSONObject();
        String jsonStr=null;
        if (httpEntity!=null) {
            BufferedReader reader=null;
            try {
                reader=new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024);
                String line=null;
                while ((line=reader.readLine())!=null) {
                    entityStringBuilder.append(line);
                }
                // 從HttpEntity中得到的json String資料轉為json
                jsonStr=entityStringBuilder.toString();
                resultJsonObject=JSON.parseObject(jsonStr);
            } catch (JSONException e) {
                //如果不是json格式的,應該是表單鍵值對格式,直接put到formData
                resultJsonObject.put("formData",jsonStr);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        //關閉流
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return resultJsonObject;
    }

    /**
     * 將httpResponse物件轉換為自定義的BaseResponse物件
     * @param httpResponse
     * @return
     */
    public BaseResponse httpResponseToBaseResponse(CloseableHttpResponse httpResponse){
        //        遍歷取出headers
        JSONArray headList = new JSONArray();
        for (Header header :httpResponse.getAllHeaders()){
            String key = header.getName();
            String value = header.getValue();
            JSONObject tempJson = new JSONObject();
            tempJson.put(key,value);
            headList.add(tempJson);
        }
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setHeaders(headList);
        baseResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        baseResponse.setResponseBody(httpEntityToJSONObject(httpResponse.getEntity()));

        return baseResponse;
    }

    /**
     * 為httpGet和httpPost加headers
     * @param httpEntityEnclosingRequestBase,HttpGet和HttpPost都是繼承這個類
     * @param headers
     * @return
     */
    public HttpEntityEnclosingRequestBase addHeaders(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase, JSONObject headers){
        //迴圈加header
        if(headers!=null) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                httpEntityEnclosingRequestBase.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        return httpEntityEnclosingRequestBase;
    }
    /**
     * 為httpGet加headers
     * @param httpRequestBase,HttpGet和HttpPost都是繼承這個類
     * @param headers
     * @return
     */
    public HttpRequestBase addHeaders(HttpRequestBase httpRequestBase, JSONObject headers){
        //迴圈加header
        if(headers!=null) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                httpRequestBase.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        return httpRequestBase;
    }

    /**
     * 為httpPost加cookies
     * @param httpEntityEnclosingRequestBase,HttpPost是繼承這個類
     * @param cookies
     * @return
     */
    public HttpEntityEnclosingRequestBase addCookies(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase,String cookies){
        //迴圈加cookies
        if(cookies!=null) {
            httpEntityEnclosingRequestBase.addHeader("Cookie", cookies);
        }
        return httpEntityEnclosingRequestBase;
    }
    /**
     * 為httpPost加cookies
     * @param httpRequestBase,HttpGet是繼承這個類
     * @param cookies
     * @return
     */
    public HttpRequestBase addCookies(HttpRequestBase httpRequestBase, String cookies){
        //迴圈加cookies
        if(cookies!=null) {
            httpRequestBase.addHeader("Cookie", cookies);
        }
        return httpRequestBase;
    }

}

 

 1 import java.io.*;
 2 import java.net.URL;
 3 import java.net.URLConnection;
 4 
 5 /**
 6  * @author kin
 7  * @version $: v 0.1 2016/8/23 Exp $$
 8  */
 9 public class httpTest {
10 
11     public static void sendGet() throws IOException {
12 
13         BufferedReader in1 = null;
14         // 1.建立URL類
15         URL urlString = new URL("https://www.baidu.com");
16 
17 
18         // 2.開啟和URL之間的連線
19         URLConnection connection1 = urlString.openConnection();
20 
21 
22         // 3.設定通用的請求屬性
23 
24             connection1.setRequestProperty("accept", "*/*");
25             connection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8;");
26             connection1.setRequestProperty("connection", "Keep-Alive");
27             connection1.setRequestProperty("user-agent", "testDemo");
28 
29             // 4.建立實際的連線
30             connection1.connect();
31 
32             // 5.定義 BufferedReader輸入流來讀取URL的響應
33             in1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
34             String line = null;
35             while ((line = in1.readLine()) != null) {
36                 System.out.println(line);
37             }
38 
39             // 6.使用finally塊來關閉輸入流
40             in1.close();
41     }
42 
43     public static void sendPost(String data) {
44         String charSet = "utf-8";
45         BufferedReader in1 = null;
46         PrintWriter out = null;
47         // 1.建立URL類
48         try {
49             URL urlPost = new URL("http://www.baidu.com");
50 
51             // 2.開啟和URL之間的連線
52 
53             URLConnection connectionPost = urlPost.openConnection();
54             // 3.設定通用的請求屬性
55             connectionPost.setConnectTimeout(30000);
56             connectionPost.setReadTimeout(30000);
57             connectionPost.setRequestProperty("accept", "*/*");
58             connectionPost.setRequestProperty("Content-Type", "application/json;charset=" + charSet);
59             connectionPost.setRequestProperty("connection", "Keep-Alive");
60             connectionPost.setRequestProperty("user-agent", "testDemoPost");
61             // 4.建立實際的連線
62             connectionPost.connect();
63 
64             // 5.傳送post請求必須設定如下兩行,設定了這兩行,就可以對URL連線進行輸入/輸出
65 
66             connectionPost.setDoInput(true);
67             connectionPost.setDoOutput(true);
68             // 6.獲取URLConnection物件對應的輸出流
69 
70             out = new PrintWriter(new OutputStreamWriter(connectionPost.getOutputStream(), charSet));
71 
72             // 7.傳送請求引數
73             out.print(data);
74 
75             // 8.清空快取區的快取
76             out.flush();
77 
78             // 9.定義 BufferedReader輸入流來讀取URL的響應
79             in1 = new BufferedReader(new InputStreamReader(connectionPost.getInputStream(), charSet));
80 
81 
82         } catch (IOException e) {
83             e.printStackTrace();
84         }// 10.使用finally塊來關閉輸入流
85         finally {
86             try {
87                 out.close();
88                 in1.close();
89             }catch(Exception e){
90                 e.printStackTrace();
91             }
92 
93         }
94     }
95     public static void main(String[] args) throws IOException {
96         httpTest.sendGet();
97     }
98 
99 }

 

轉載於:https://www.cnblogs.com/zipon/p/5799313.html

相關文章