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;
    }
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值