Java+Maven+TestNG接口(API)自動化測試教程(八) Post,Put 和 Delete 方法

8.1 發送 POST 方法

post 方法和 get 方法是我們在做接口測試時,用的最多的兩個請求方法。 在發送請求時它們顯著的一個差別就在於,get 方法我們只需要將 url 發送即可,post 我們還需發送一個請求主體;在作用方面,get 方法用於查詢,不會改變服務器中的信息;而 Post 方法可用於修改服務器中的信息。

8.1.1 修改 HttpClientUtil 實現發送 POST 請求和獲取響應

根據請求的數據是 JSON 對象還是表單形式的鍵值對,分成了 sendPostByJson 和 sendPostByForm 兩類方法,其中 sendPostByForm 方法用 ArrayList 存儲 NameValuePair 鍵值對,再設置請求的主體;sendPostByJson 方法將對象序列化爲 JONS 字符串,再設置請求的主體。

public JSONObject sendPostByJson(String url, Object object, HashMap<String, String> headers) throws Exception {
    httpClient = HttpClients.createDefault(); 
    HttpPost httpPost = new HttpPost(url); 
    try {
        httpPost.setConfig(requestConfig);
        String json = JSON.toJSONString(object);
        StringEntity entity = new StringEntity(json, "utf-8");         
        entity.setContentType("application/json"); httpPost.setEntity(entity);
        if (headers != null) {
            // 加載請求頭到httppost對象
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        response = httpClient.execute(httpPost); 
        HttpEntity responseEntity = response.getEntity(); String result = null;
        if (responseEntity != null) {
            result = EntityUtils.toString(responseEntity, "UTF-8");
        }
        EntityUtils.consume(responseEntity); 
        JSONObject jsonobj = JSON.parseObject(result);
        jsonobj.put(HTTPSTATUS, response.getStatusLine().getStatusCode());
        return jsonobj;
    } finally {
        httpClient.close(); 
        response.close();
    }
}

public JSONObject sendPostByForm(String url, Map<String, String> form, HashMap<String, String> headers) throws Exception {
    httpClient = HttpClients.createDefault(); 
    HttpPost httpPost = new HttpPost(url); 
    try {
        httpPost.setConfig(requestConfig);
        // 設置請求主體格式
        if (form.size() > 0) {
            ArrayList<BasicNameValuePair> list = new ArrayList<>();
            form.forEach((key, value) -> list.add(new BasicNameValuePair(key, value)));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
        }
        entity.setContentType("application/x-www-form-urlencoded"); 
        httpPost.setEntity(entity);
        if (headers != null) {
            // 設置頭部信息
            Set<String> set = headers.keySet();
            for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
                String key = iterator.next(); 
                String value = headers.get(key); 
                httpPost.setHeader(key, value);
            }
        }
        response = httpClient.execute(httpPost); 
        HttpEntity entity = response.getEntity(); 
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, "utf-8");
        }
        EntityUtils.consume(entity);
        JSONObject jsonobj = JSON.parseObject(result);
        jsonobj.put(HTTPSTATUS, response.getStatusLine().getStatusCode());
        return jsonobj;
    } finally {
        httpClient.close(); response.close();
    }
}

public JSONObject sendPostByForm(String url, Map<String, String> form)
throws Exception {
    return sendPostByForm(url, form, null);
}

public JSONObject sendPostByJson(String url, Object object) throws Exception {
    return sendPostByJson(url, object, null);
}

8.2  發送 Put 方法請求和獲取響應

Put 方法請求基本上和 sendPostByForm 方法內容一致,只是將 HttpPost 類換做了HttpPut 類。

public JSONObject sendPut(String url, String entityString, HashMap<String, String> headers)throws ClientProtocolException, IOException {
    httpClient = HttpClients.createDefault(); 
    HttpPut httpPut = new HttpPut(url);
    try {
        httpPut.setConfig(requestConfig);
        httpPut.setEntity(new StringEntity(entityString, "utf-8"));
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPut.setHeader(entry.getKey(), entry.getValue());
            }
        }
    // 發送put請求
    response = httpClient.execute(httpPut); 
    HttpEntity entity = response.getEntity(); 
    String result = null;
    if (entity != null) {
        result = EntityUtils.toString(entity, "utf-8");
    }
    EntityUtils.consume(entity);
    JSONObject jsonobj = JSON.parseObject(result);
    jsonobj.put(HTTPSTATUS, response.getStatusLine().getStatusCode());
    return jsonobj;
    } finally {
        httpClient.close(); response.close();
    }
}

8.3 發送 Delete 方法

Delete  方法更加簡單了,它用於刪除服務器上的資源,所以執行後只需要返回響應狀態碼即可。

public int sendDelete(String url) throws ClientProtocolException, IOException {
    httpClient = HttpClients.createDefault(); 
    HttpDelete httpDel = new HttpDelete(url); 
    try {
        httpDel.setConfig(requestConfig);
        // 發送delete請求
        response = httpClient.execute(httpDel);
        int statusCode = response.getStatusLine().getStatusCode();
        return statusCode;
    } finally {
        httpClient.close(); 
        response.close();
    }
}

8.4 相關源代碼

8.4.1 用於給 sendPostByJson 方法傳遞對象的 User 類:

package com.mytest.httpclient;
public class Uses { 
    private String name; 
    private String job; 
    public User() {
        super();
    }
    public User(String name, String job) {
        super(); 
        this.name = name; 
        this.job = job;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
}

8.4.2 TestNG 測試類源代碼:

package com.mytest.httpclient.test;

import java.io.IOException; 
import java.util.HashMap; 
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.CloseableHttpResponse; 
import org.apache.http.impl.client.CloseableHttpClient; 
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.mytest.httpclient.HttpClientUtil;
import com.mytest.httpclient.Users; 
import com.mytest.httpclient.Util; 
import com.alibaba.fastjson.JSON; 
import com.alibaba.fastjson.JSONObject; 

public class RequestMethodTest {
    CloseableHttpClient client; 
    CloseableHttpResponse closeableHttpResponse; 
    HttpEntity responseBody;
    int responseCode; 
    HttpClientUtil hcu; 
    String url;

    @BeforeTest
    public void setUp() {
        hcu = new HttpClientUtil ();
    }

    @Test
    public void postByFormTest() throws Exception {
        url = "https://reqres.in/api/login";
        Map<String,String> params = new HashMap<String,String>(); 
        params.put("email", "[email protected]"); 
        params.put("password", "cityslicka");
        JSONObject responseJson = hcu.sendPostByForm(url, params);
        // 驗證狀態碼是不是200
        int statusCode = responseJson.getInteger(hcu.HTTPSTATUS);
        Assert.assertEquals(statusCode, HttpStatus.SC_OK, "status code is not 201");
        // 斷言響應json內容中name和job是不是期待結果 
        String token = Util.getValueByJPath(responseJson, "token");
        Assert.assertEquals(token, "QpwL5tke4Pnpja7X4", "token is not right");
    }

    @Test
    public void postByJsonTest() throws Exception {
        // 對象轉換成Json字符串
        User user = new User("Anthony", "tester");
        url = "https://reqres.in/api/users";
        JSONObject responseJson = hcu.sendPostByJson(url, user);
        // 驗證狀態碼是不是201
        int statusCode = responseJson.getInteger(hcu.HTTPSTATUS);
        Assert.assertEquals(statusCode, HttpStatus.SC_CREATED, "status code is not 201");
        // 斷言響應json內容中name和job是不是期待結果
        String name = Util.getValueByJPath(responseJson, "name"); 
        String job = Util.getValueByJPath(responseJson, "job"); 
        Assert.assertEquals(name, "Anthony", "name is not same");             
        Assert.assertEquals(job, "tester", "job is not same");
    }

    @Test
    public void putTest() throws ClientProtocolException, IOException {
        url = "https://reqres.in/api/users/2";
        HashMap<String, String> headermap = new HashMap<String, String>();
        // 這個在postman 中可以查詢到
        headermap.put("Content-Type", "application/json");   
        // 對象轉換成Json字符串
        Users user = new Users("Anthony", "automation tester"); 
        String userJsonString = JSON.toJSONString(user);
        JSONObject responseJson = hcu.sendPut(url, userJsonString, headermap);
        // 驗證狀態碼是不是200
        int statusCode = responseJson.getInteger(hcu.HTTPSTATUS);
        Assert.assertEquals(statusCode, HttpStatus.SC_OK, "response status code is not 200");
        // 驗證名稱爲Anthony的jon是不是 automation tester
        String jobString = Util.getValueByJPath(responseJson, "job");                     
        Assert.assertEquals(jobString, "automation tester", "job is not same");
    }

    @Test
    public void deleteApiTest() throws ClientProtocolException, IOException
    {
        url = "https://reqres.in/api/users/2";
        int statusCode = hcu.sendDelete(url); 
        Assert.assertEquals(statusCode,   HttpStatus.SC_NO_CONTENT, "status code is not 204");
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章