HttpClient是模擬Http協議客戶端請求的一種技術,可以發送Get/Post等請求。 所以在學習HttpClient測試框架之前,先來看一下Http協議請求,主要看請求頭信息。
如何查看HTTP協議請求頭信息: 打開瀏覽器-->輸入任意一個網址-->按下F12 打開開發者工具-->Network-->刷新頁面,可以在Network看到有Get或者post請求的URL,點擊URL,可以看到該請求的Header/Cookies/Response等信息
例如我們打開www.baidu.com,查看它某個請求的信息,如下:

常用的請求頭和響應頭信息解釋:


下面通過一個簡單的例子學習HttpClient
import java.io.IOException; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.methods.HttpGet; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.testng.annotations.Test; public class MyHttpClient { @Test public void test1() { String result; HttpGet get = new HttpGet("http://localhost:8888/getCookies"); DefaultHttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(get); result = EntityUtils.toString(response.getEntity()); CookieStore cookieStore = client.getCookieStore(); List<Cookie> cookies =cookieStore.getCookies(); System.out.println(cookies.size()); for(Cookie c :cookies) {//get Cookies info System.out.println(c.getName() + ":" + c.getValue()); } } catch (IOException e) { e.printStackTrace(); } } }
Run TestNG Test, 可以看到返回的result是HTML源碼。這個是通過HttpClient Get請求方法實現的簡單例子。下面結合Mock模擬數據,學習如何使用HttpClient。
Mock一個返回Cookies信息的請求:
{
"description":"This get request with cookies return",
"request":{
"uri":"/getCookies",
"method":"get"
},
"response":{
"cookies":{
"login":"true"
},
"text":"This is response with cookies"
}
}
具體如何Mock數據可以參考上一篇文章《Mock接口平台Moco學習》.
我們已經知道如何從服務端獲取 Cookie信息了,那下一步學習客戶端如何使用拿到的Cookie信息。
首先在Mock一個接口,這是攜帶/getCookies 接口返回的Cookies信息Get請求的接口:
{
"description":"This is Get request with cookies",
"request":{
"uri":"/get/with/cookies",
"method":"get",
"cookies":{
"login":"true"
}
},
"response":{
"text":"This is response for get request with cookies"
}
}
完整的代碼:
import java.io.IOException; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.methods.HttpGet; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.testng.annotations.Test; public class MyHttpClient { private CookieStore cookieStore; @Test public void test1() { String result; HttpGet get = new HttpGet("http://localhost:8888/getCookies"); DefaultHttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(get); result = EntityUtils.toString(response.getEntity()); System.out.println("result=" + result); cookieStore = client.getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); System.out.println(cookies.size()); for (Cookie c : cookies) { System.out.println(c.getName() + ":" + c.getValue()); } } catch (IOException e) { e.printStackTrace(); } } @Test(dependsOnMethods = { "test1" }) public void testGetWithCookie() { HttpGet get = new HttpGet("http://localhost:8888/get/with/cookies"); DefaultHttpClient client = new DefaultHttpClient(); // Set cookie info client.setCookieStore(cookieStore); try { HttpResponse response = client.execute(get); // get response status int statusCode = response.getStatusLine().getStatusCode(); // statusCode = 200 / 404 / 502..... System.out.println("Status = " + statusCode); if (statusCode == 200) { // Success String result = EntityUtils.toString(response.getEntity()); System.out.println("result=" + result); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
HttpClient Post請求的實現:
首先還是Mock一個post請求
{
"description":"This is Post request with cookies",
"request":{
"uri":"/post/with/cookies",
"method":"post",
"cookies":{
"login":"true"
},
"json":{
"name":"zhangsan",
"age":"18"
}
},
"response":{
"status":200,
"json":{
"zhangsan":"success",
"status":"1"
}
}
}
完整的Post請求代碼:
import java.io.IOException; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.cookie.Cookie; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONObject; import org.testng.Assert; import org.testng.annotations.Test; public class MyCookiesForPost { private CookieStore cookieStore; @Test public void test1() { String result; HttpGet get = new HttpGet("http://localhost:8888/getCookies"); DefaultHttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(get); result = EntityUtils.toString(response.getEntity()); System.out.println("result=" + result); cookieStore = client.getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); System.out.println(cookies.size()); for (Cookie c : cookies) { System.out.println(c.getName() + ":" + c.getValue()); } } catch (IOException e) { e.printStackTrace(); } } @Test(dependsOnMethods = { "test1" }) public void testPostWithCookie() { //1. Define a client to excute //2. Define a post method //3. Add pamarater //4. Set request header info; set cookie inof //5. Execute //6. Get and handle Result //7. assert result DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://localhost:8888/post/with/cookies"); JSONObject param = new JSONObject(); param.put("name", "zhangsan"); param.put("age", "18"); StringEntity entity = new StringEntity(param.toString(),"utf-8"); post.setEntity(entity); post.addHeader("content-type", "application/json"); client.setCookieStore(cookieStore); try { HttpResponse response = client.execute(post); String result = EntityUtils.toString(response.getEntity()); System.out.println("result=" + result); JSONObject object = new JSONObject(result); System.out.println("zhangsan=" + object.getString("zhangsan")); System.out.println("status=" + object.getString("status")); String actualResult = object.getString("zhangsan"); Assert.assertEquals(actualResult,"success"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
代碼優化: 在實際的測試過程當中,我們一般不會直接將請求地址寫在請求對象當中。而是定義在配置文件中,然后在代碼中引用。具體用法如下。
創建一個.properties文件,如config.properties:
test.url=http://localhost:8888
然后在代碼中讀取該config.properties,並獲取相應的地址:
private ResourceBundle bundle; private String url; @BeforeTest public void beforeTest() { bundle = ResourceBundle.getBundle("config"); url = bundle.getString("test.url"); }
以上是HttpClient的常見用法和其中一個優化方案。
如果喜歡作者的文章,請關注"寫代碼的猿"訂閱號以便第一時間獲得最新內容。本文版權歸作者所有,歡迎轉載.

我的博客即將同步至騰訊雲+社區,邀請大家一同入駐:https://cloud.tencent.com/developer/support-plan?invite_code=2wrsyxyyavcwc
