1. 程式人生 > >Java程式碼發起HTTP GET和POST請求(URLConnection)

Java程式碼發起HTTP GET和POST請求(URLConnection)

背景:在使用java語言寫介面自動化用例的時候,經常用到程式碼直接發起HTTP請求,從而得到響應內容,通過斷言響應內容,判斷介面返回是否正確。
方法:java實現HTTP請求主要有兩種方法,一是用JDK自帶類URLConnection、二是用第三方jar包httpclient,本篇介紹URLConnection如何實現發起HTTP請求。

一、URLConnection發起請求步驟
1.開啟和URL之間的連線

URLConnection connection = new URL("請求url地址").openConnection();
HttpURLConnection httpUrlConnection = (HttpURLConnection)connection;

2.設定請求方式

conn.setRequestMethod(“GET”)

3.設定通用的請求屬性
connection.setRequestProperty("Accept-Charset", charset);
4. 建立實際的連線

connection.connect();

5.獲取響應頭部,遍歷輸出

Map<String,List<String>> map = connection.getHeaderFields();
for (Map.Entry<String, List<String>> header :       connection.
getHeaderFields().entrySet()) { System.out.println(header.getKey() + "=" + header.getValue()); }

6.獲取響應碼,響應訊息

int resCode = httpUrlConnection.getResponseCode();
String message = httpUrlConnection.getResponseMessage();

7.列印response body

    //方式一、定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new
InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) result += "\n" + inputLine; System.out.println("result===" + result);

二、完整GET請求程式碼

/**
    *   向指定URL傳送GET方法的請求,請求引數可有可無
    *   
    *   @ url 傳送請求的url
    *   @ param1/2 請求引數,可有可無,格式必須是name1=value1&name2=value2
    *   @ return 請求響應內容
    */
    public static String sendGet(String url, String param) throws Exception {

        String result = "";
        BufferedReader in = null;

        try{
            String charset = java.nio.charset.StandardCharsets.UTF_8.name();
            //String query = String.format("param1=%s",URLEncoder.encode(param1, charset));

            //若是兩個請求引數,使用param1=%s&param2=%s
            //String query = String.format("wd=%s&param2=%s",URLEncoder.encode(param1, charset),URLEncoder.encode(param2, charset));

            String request = url + "?" + param;

            //開啟和URL之間的連線 
            URLConnection connection = new URL(request).openConnection();

            /* begin獲取響應碼 */
            HttpURLConnection httpUrlConnection = (HttpURLConnection)connection;
            httpUrlConnection.setConnectTimeout(300000);
            httpUrlConnection.setReadTimeout(300000);
            httpUrlConnection.connect();
            //獲取響應碼 =200
            int resCode = httpUrlConnection.getResponseCode();
            //獲取響應訊息 =OK
            String message = httpUrlConnection.getResponseMessage();

            System.out.println("getResponseCode resCode ="+ resCode);
            System.out.println("getResponseMessage message ="+ message);
            /* end獲取響應碼 */

            /* begin獲取響應headers*/
            System.out.println("響應頭:" + result);
            for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
                System.out.println(header.getKey() + "=" + header.getValue());
            }
            /* end獲取響應headers*/

            /* begin獲取響應內容 /
            if (resCode == httpUrlConnection.getResponseCode()) {
                int contentLength = httpUrlConnection.getContentLength();  
                System.out.println("contentLength--->" + contentLength);
                if(contentLength > 0){
                    in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) 
                        result += "\n" + inputLine;   
                    System.out.println("響應內容:" + result);
                }
            } 
            /* end獲取響應內容 */

            /*
            //設定通用的請求屬性
            connection.setRequestProperty("Accept-Charset", charset);
            //建立實際的連線  
            connection.connect();
            //獲取響應頭部
            Map<String,List<String>> map = connection.getHeaderFields();
            System.out.println("\n顯示響應Header資訊...\n");
            //遍歷所有的響應頭欄位並輸出
            //方式一、
            for (String key : map.keySet()) {  
                System.out.println(key + " : " + map.get(key));  
            }  
            //方式二、
            for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
                System.out.println(header.getKey() + "=" + header.getValue());
            }
            */
            //列印response body
            //方式一、定義BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) 
                result += "\n" + inputLine; 
            System.out.println("result===" + result);  
            /*
            //方式二、使用Scanner
            System.out.println("響應內容:");
            InputStream response = connection.getInputStream();

            try(Scanner scanner = new Scanner(response)) {
                String responseBody = scanner.useDelimiter("\\A").next();
                System.out.println(responseBody);
            }*/

            //解析響應json
            JSONObject json = JSONObject.parseObject(result/*"待解析的json字串"*/); 
            System.out.println(JSONObject.toJSONString(json, true));
        }catch (Exception e){
            System.out.println("傳送GET請求出現異常!" + e);  
            e.printStackTrace();
        }// 使用finally塊來關閉輸入流  
        finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
            } catch (IOException ex) {  
                ex.printStackTrace();  
            }  
        }  

        return result;
    }