• 【接口】HttpClient 处理get和post请求(二)(2019-07-14 18:41)


    一、环境准备

    1.导入httpClient依赖包

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
    </dependency>

     导入fastJson依赖实现实体类序列化和json反序列操作

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.54</version>
    </dependency>

    testng依赖

    <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8.8</version>
            <scope>test</scope>
    </dependency>

    二、Get请求发包代码实现

    package test;
    
    import java.util.Arrays;
    import java.util.HashMap;
    
    import org.apache.http.Header;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import org.testng.Assert;
    import org.testng.annotations.Test;
    
    import com.alibaba.fastjson.JSONObject;
    
    public class HttpClientTest {
        String url = "http://localhost:8081/user/login";
        String get_params = "username=xiaobing&password=123456";
        @Test
        public  void GetTest() {
            //创建HttpGet对象
            HttpGet httpGet = new HttpGet(url+"?"+get_params);
            //准备HttpClient客户端
            CloseableHttpClient httpClient =HttpClients.createDefault();
            CloseableHttpResponse httpResponse = null;
            try {
                //发送请求
                httpResponse  = httpClient.execute(httpGet);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //取出响应状态码
            int code = httpResponse.getStatusLine().getStatusCode();
            System.out.println("响应码:"+code);
            //取出消息头
            Header[] header = httpResponse.getAllHeaders();
            System.out.println("消息头:"+Arrays.toString(header));
            //取出响应报文
            String result = null;
            try {
                //使用EntityUtils工具类将Entity实体类toString转换
                result = EntityUtils.toString(httpResponse.getEntity());
                System.out.println("响应报文:"+result);
            } catch (Exception e) {
                e.printStackTrace();
            } 
            HashMap<String, String> map  = JSONObject.parseObject(result, HashMap.class);
            String actual = map.get("message");
            System.out.println("actual_message:"+actual);
            String expected = "登录成功";
            //断言
            Assert.assertEquals(actual, expected);
        }
    }
    响应码:200
    消息头:[Content-Type: application/json;charset=UTF-8, Transfer-Encoding: chunked, Date: Sun, 14 Jul 2019 14:06:44 GMT]
    响应报文:{"status":"1","message":"登录成功"}
    actual_message:登录成功
    PASSED: GetTest
    ===============================================
        Default test
        Tests run: 1, Failures: 0, Skips: 0
    ===============================================
    ===============================================
    Default suite
    Total tests run: 1, Failures: 0, Skips: 0
    ===============================================

    三、POST请求发包代码实现(表单方式)

    服务端:

    @RestController//控制器类
    @RequestMapping("/user")//映射路径
    public class UserController {
        @RequestMapping(value="/login",method=RequestMethod.POST,consumes="application/x-www-form-urlencoded")
        public Result login(User user) {
       。。。 。。。
    }

    客户端:

    @Test
    public void postFormSend() {
        //测试数据准备
        String url = "http://localhost:8081/user/login";
        String params = "username=xiaobing&password=123456";
        //创建HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        //将Content-Type类型添加到消息头
        Header header = new BasicHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
        httpPost.addHeader(header);
        //将表单参数添加到Entity实体类放到请求体
        HttpEntity entity = new StringEntity(params, "UTF-8");
        httpPost.setEntity(entity);
        //准备HttpClient客户端
        CloseableHttpClient httpClient =HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            //发起请求
            httpResponse =httpClient.execute(httpPost);
        } catch (Exception e) {
            e.printStackTrace();
        } 
        int code = httpResponse.getStatusLine().getStatusCode();
        System.out.println("响应码:"+code);
        Header[] resHeader = httpResponse.getAllHeaders();
        System.out.println("消息头:"+Arrays.toString(resHeader));
        HttpEntity httpEntity = httpResponse.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(httpEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("响应报文:"+result);
        HashMap<String, String> map  = JSONObject.parseObject(result, HashMap.class);
        String actual = map.get("message");
        System.out.println("actual_message:"+actual);
        String expected = "登录成功";
        //断言
        Assert.assertEquals(actual, expected);
        
    }
    响应码:200
    消息头:[Content-Type: application/json;charset=UTF-8, Transfer-Encoding: chunked, Date: Sun, 14 Jul 2019 15:13:53 GMT]
    响应报文:{"status":"1","message":"登录成功"}
    actual_message:登录成功
    PASSED: postFormSend
    ===============================================
        Default test
        Tests run: 1, Failures: 0, Skips: 0
    ===============================================
    ===============================================
    Default suite
    Total tests run: 1, Failures: 0, Skips: 0
    ===============================================

    四、POST请求发包代码实现(Json方式)

    服务端:

    @RestController//控制器类
    @RequestMapping("/user")//映射路径
    public class UserController {
        @RequestMapping(value="/login",method=RequestMethod.POST,consumes="application/json")
        public Result login(@RequestBody(required=false)User user) {
    。。。 。。。
    }

    客户端:

    @Test
    public void postJsonSend() {
        //测试数据准备
        String url = "http://localhost:8081/user/login";
        String params = "{"username":"xiaobing","password":"123456"}";
        //创建HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        //将Content-Type类型添加到消息头
        Header header = new BasicHeader("Content-Type","application/json;charset=utf-8");
        httpPost.addHeader(header);
        //将表单参数添加到Entity实体类放到请求体
        HttpEntity entity = new StringEntity(params, "UTF-8");
        httpPost.setEntity(entity);
        //准备HttpClient客户端
        CloseableHttpClient httpClient =HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            //发起请求
            httpResponse =httpClient.execute(httpPost);
        } catch (Exception e) {
            e.printStackTrace();
        } 
        int code = httpResponse.getStatusLine().getStatusCode();
        System.out.println("响应码:"+code);
        Header[] resHeader = httpResponse.getAllHeaders();
        System.out.println("消息头:"+Arrays.toString(resHeader));
        HttpEntity httpEntity = httpResponse.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(httpEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("响应报文:"+result);
        HashMap<String, String> map  = JSONObject.parseObject(result, HashMap.class);
        String actual = map.get("message");
        System.out.println("actual_message:"+actual);
        String expected = "登录成功";
        //断言
        Assert.assertEquals(actual, expected);
        
    }
    响应码:200
    消息头:[Content-Type: application/json;charset=UTF-8, Transfer-Encoding: chunked, Date: Sun, 14 Jul 2019 15:18:53 GMT]
    响应报文:{"status":"1","message":"登录成功"}
    actual_message:登录成功
    PASSED: postJsonSend
    ===============================================
        Default test
        Tests run: 1, Failures: 0, Skips: 0
    ===============================================
    ===============================================
    Default suite
    Total tests run: 1, Failures: 0, Skips: 0
    ===============================================

    五、代码整合

    未完待续。。。

  • 相关阅读:
    莫队
    NOIP2010_T4_引水入城 bfs+贪心
    拉灯游戏 搜索
    种花小游戏 随机化搜索
    [usaco2003feb]impster
    P1265 公路修建 (prim)
    P3378 【模板】堆
    并查集 模板
    P2661 信息传递
    P1828 香甜的黄油 Sweet Butter (spfa)
  • 原文地址:https://www.cnblogs.com/xiaozhaoboke/p/11185270.html
Copyright © 2020-2023  润新知