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

1、環境準備java

1.導入httpClient依賴包apache

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

 導入fastJson依賴實現實體類序列化和json反序列操做json

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

testng依賴app

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

2、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
===============================================

3、POST請求發包代碼實現(表單方式)post

服務端:測試

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

客戶端:ui

@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
===============================================

4、POST請求發包代碼實現(Json方式)url

服務端:spa

@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
===============================================

5、代碼整合

未完待續。。。

相關文章
相關標籤/搜索