接口自动化测试框架HttpClient-2-GetPost请求

Get请求

1.请求Url

2.请求参数

3.请求header

4.响应结果断言

5.响应数据提取

  public static void getDefault(String url){
        //创建一个可关闭的HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //创建一个HttpGet的请求对象
        HttpGet httpget = new HttpGet(url);
        //执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpclient.execute(httpget);
            //拿到Http响应状态码,例如和200,404,500去比较
            int responseStatusCode = httpResponse.getStatusLine().getStatusCode();
            logger.info("response status code -->"+responseStatusCode);

            //把响应内容存储在字符串对象
            String responseString = EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
            //创建Json对象,把上面字符串序列化成Json对象
            JSONObject responseJson = JSON.parseObject(responseString);
            logger.info("respon json from API-->" + responseJson);

            //获取响应头信息,返回是一个数组
            Header[] headerArray = httpResponse.getAllHeaders();
            //创建一个hashmap对象,通过postman可以看到请求响应头信息都是Key和value得形式,所以我们想起了HashMap
            HashMap<String, Object> hm = new HashMap<String, Object>();
            //增强for循环遍历headerArray数组,依次把元素添加到hashmap集合
            for(Header header : headerArray) {
                hm.put(header.getName(), header.getValue());
            }
            JSONObject jsonObject = JsonUtil.mapTransTOJSON(hm);
            logger.info("jsonObject:"+jsonObject);
            String json=JsonUtil.ObjectToJson(jsonObject);
            logger.info("json:"+json);
            logger.info("jsonString:"+JsonUtil.getJSONString(jsonObject));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

上面的代码可以作为学习get请求的过程,在实际开发中我们只关注get请求的url和传入的参数,获取请求的响应内容:

不带参数的请求:

public static CloseableHttpResponse get(String url){
        //创建一个可关闭的HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //创建一个HttpGet的请求对象
        HttpGet httpget = new HttpGet(url);
        //执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpclient.execute(httpget);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpResponse;
    }

带请求头的get请求 

 public static CloseableHttpResponse getWithHead(String url,Map<String,String> headermap)  {

        //创建一个可关闭的HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        //加载请求头到httpget对象
        for(Map.Entry<String, String> entry : headermap.entrySet()) {
            httpget.addHeader(entry.getKey(), entry.getValue());
        }
        //执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpclient.execute(httpget);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpResponse;
    }

get请求带有参数:

public static CloseableHttpResponse getWithParams(String url,List<BasicNameValuePair>pairs)  {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            URIBuilder uriBuilder=new URIBuilder(url);
            for (int i=0;i<pairs.size();i++) {
                uriBuilder.setParameters((NameValuePair) pairs.get(i));
            }
            HttpGet httpget = new HttpGet(uriBuilder.toString());
            //执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收
            CloseableHttpResponse httpResponse = httpclient.execute(httpget);
            return httpResponse;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;


    }

 

post请求和get请求不同,post请求的参数部分封装在body请求里面,这里可以把参数信息写进map里或者直接读取json,yaml都是可选择的


    /**
     * 参数在map里
     * @param url
     * @param paramsmap
     * @param headermap
     * @return
     */
    public static  CloseableHttpResponse post(String url, HashMap<String,Object>paramsmap, HashMap<String,String> headermap){
        //创建一个可关闭的HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //创建一个HttpPost的请求对象
        HttpPost httppost = new HttpPost(url);

        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();

        try {
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
            logger.info("formEntity:"+formEntity);
            // 第一步:通过setEntity 将我们的entity对象传递过去
            httppost.setEntity(new StringEntity(JsonUtil.MapToJsonString(paramsmap)));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        //加载请求头到httppost对象
        for(Map.Entry<String, String> entry : headermap.entrySet()) {
            httppost.addHeader(entry.getKey(), entry.getValue());
        }
        //发送post请求
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpResponse;
    }

 json请求封装

/**
     * 直接请求数据是json数据
     * @param url
     * @param headermap
     * @param jsonObject
     * @return
     */
    public static  CloseableHttpResponse post(String url, HashMap<String,String> headermap,String jsonObject){
        //创建一个可关闭的HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //创建一个HttpPost的请求对象
        HttpPost httppost = new HttpPost(url);
        try {
            // 第一步:通过setEntity 将我们的entity对象传递过去
            httppost.setEntity(new StringEntity(jsonObject));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //加载请求头到httppost对象
        for(Map.Entry<String, String> entry : headermap.entrySet()) {
            httppost.addHeader(entry.getKey(), entry.getValue());
        }
        //发送post请求
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpclient.execute(httppost);
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpResponse;
    }

上面封装的方法可以解决实际项目中遇到的大部分问题,通过获取响应的response,可以为后面的接口请求传递参数

根据Response获取对应响应状态和响应信息:


    /**
     * 获取响应code 200
     * @param httpResponse
     * @return
     */
     public static int getStatusCode(CloseableHttpResponse httpResponse ){
         return  httpResponse.getStatusLine().getStatusCode();
     }

    /**
     * 得到响应字符串
     * @param httpResponse
     * @return
     */
     public static String getResponseString(CloseableHttpResponse httpResponse){
         try {
             return  EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
         } catch (IOException e) {
             e.printStackTrace();
         }
         return  null;
     }
    /**
     * 得到所有的响应头
     * @param httpResponse
     * @return
     */
    public static Header[] getResHeader(CloseableHttpResponse httpResponse){
            return  httpResponse.getAllHeaders();
    }

附加上put delete请求  这里做下了解

 /**
     * put请求
     * @param url
     * @param entityString
     * @param headerMap
     * @return
     */
    public static CloseableHttpResponse put(String url, String entityString, HashMap<String, String> headerMap)  {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPut httpput = new HttpPut(url);
        CloseableHttpResponse httpResponse =null;
        try {
            httpput.setEntity(new StringEntity(entityString));
            for(Map.Entry<String, String> entry : headerMap.entrySet()) {
                httpput.addHeader(entry.getKey(), entry.getValue());
            }
            //发送put请求
            httpResponse= httpclient.execute(httpput);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return httpResponse;
    }

    /**
     * delete请求
     * @param url
     * @return
     */
    public static CloseableHttpResponse delete(String url) {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpDelete httpdel = new HttpDelete(url);

        //发送dellete请求
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpclient.execute(httpdel);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpResponse;
    }

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员路同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值