• 接口测试(二)—HttpClient


    使用HttpClient进行接口测试,所需要使用的相关代码

    HttpClient进行接口测试
    所需jar包:httpclient.jar、httpcore.jar、commons-logging.jar
    Get请求:
    //创建httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    //如果发送的是GET请求,创建HttpGet对象
    HttpGet httpget = new HttpGet("http://www.baidu.com/");
    //执行GET请求
    CloseableHttpResponse response = httpClient.execute(httpget);

    POST请求:
    CloseableHttpClient httpClient = httpClients.createDefault();
    //如果发送是POST请求,创建HttpPost对象
    HttpPost httppost = new HttpPost("http://localhost:8080/login");
    //post请求参数配置
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("name","xxx"));
    formparams.add(new BasicNameValuePair("pwd","123456"));
    //设置编码格式为utf-8
    UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams,"UTF-8");
    httppost.setEntity(uefEntity);//设置POST请求参数
    //使用httpclient的execute方法发送接口请求
    CloseableHttpResponse response = new httpClient.execute(httppost);

    创建HttpClient对象、response对象操作完毕后,需要进行释放
    //释放连接
    response.close();
    httpClient.close();

    常用方法:
    1、设置请求和连接超时时间
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
    //get请求设置请求和传输超时时间
    httpget.setConfig(requestConfig);
    //post请求设置请求和传输超时时间
    httppost.setConfig(requestConfig);

    2、获取响应头信息
    Header headers[] = response.getAllHeaders();
        for(Header header:headers){
        //响应头信息名称
        System.out.println(header.getName());
        //头信息对应的值
        System.out.println(header.getValue());
        }

    3、获取服务器指定头名称的响应头信息
    Header Serverheaders[] = response.getHeaders("Server");

    4、获取服务器返回状态码,如果等于200就说明请求和响应都成功了
    response.getStatusLine().getStatusCode();
    常见的错误码:
    200 请求成功,且请求的信息包含在响应中
    400 服务器未能识别请求
    404 请求的资源不在服务器上
    500 请求发生了错误

    5、根据主机名获取其可能的所有服务器实际ip地址(可能包含多个服务器)
    InetAddress[] address = InetAddress.getAllByName("www.baidu.com");
        for(int i = 0; i < address.length; i++){
            System.out.println(address[]);
        }

    6、调用HttpResponse的getEntity()方法可获取HttpEntity对象,服务器的响应内容
    String returnStr = EntityUtils.toString(response.getEntity());
    (常见的服务器返回的响应内容一般有:xml、json格式等)

    服务器响应内容解析
    1、使用JSONObject插件处理xml、json响应数据
    2、需要6个jar包:json-lib.jar、commons-beanutils.jar、commons-collections.jar、ezmorph.jar、commons-logging.jar、commons-logging.jar
    xom.jar  把xml的数据转换成json的数据
    String xml = "<?xml version="1.0"encoding="UTF-8"?><users><password>123456</password><username>xxx</username></users>";
    XMLSerializer xmlSerializer = new XMLSerializer();
    //使用xmlSerializer.read()方法可以将xml格式的数据转换成json格式数据
    JSON json = xmlSerializer.read(xml);
    //转换而成的JSON数据
    {"password":"123456","username":"xxx"}

    JSON常用解析方法
    //将json字符串转换为JSONObject对象
    JSONObject jsonObj = JSONObjec.fromObject(json字符串);
    //获取name对应的值
    jsonObj.getString("name");//取到节点对应的值xxx   jsonObj.getInt(XXX);
    //判断json字符串中是否包含name节点,如果存在返回true
    jsonObj.has("name");

    解析复杂的结果
    {
        "returncode":0,
        "message":"",
        "count":2,
        "result":{
            "users":[{"pwd":"123456","name":"xxx"},
                {"pwd":"123456","name":"aaa"}]
            }
        }

    //将json字符串转换为JSONObject对象
    JSONObject jsonObj = JSONObject.fromObject(json字符串);
    //result是一个json对象,使用getJSONObject()来获取
    JSONObject resultobj =jsonObj.getJSONObject("return");
    //users是数组对象的话可以使用getJSONArray()来获取一个json数组
    JSONArray userlist = resultobj.getJSONArray("users");
    //可以循环获取数组中的对象元素
    for(Object object:userlist){
        JSONObject user = (JSONObject)object;
        User.getString("pwd");
        User.getString("name");
    }

  • 相关阅读:
    定位
    supervisor进程管理工具
    简单git使用命令
    django + Vue项目上线部署
    Vue配置浏览器头部图标和title
    vue打包项目后 谷歌浏览器可以打开,其他浏览器不行
    js反向解析爬取企**网站
    python常用排序算法
    python脚本demo
    request模块封装
  • 原文地址:https://www.cnblogs.com/lebb1993/p/5866704.html
Copyright © 2020-2023  润新知