httpclient小結

一、httpclient簡介

HttpClient 是Apache Jakarta Common 下的子項目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本和建議。

二、在idea中pom文件配置

<dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20170516</version>
        </dependency>
    </dependencies>

三、使用方法

使用HttpClient發送請求、接收響應,一般需要如下幾步即可。

1. 創建HttpClient對象。

2. 創建請求方法的實例,並指定請求URL。如果需要發送GET請求,創建HttpGet對象;如果需要發送POST請求,創建HttpPost對象。

3. 如果需要發送請求參數,可調用HttpGet、HttpPost共同的setParams(HetpParams params)方法來添加請求參數;對於HttpPost對象而言,也可調用setEntity(HttpEntity entity)方法來設置請求參數。

4. 調用HttpClient對象的execute(HttpUriRequest request)發送請求,該方法返回一個HttpResponse。

5. 調用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務器的響應頭;調用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務器的響應內容。程序可通過該對象獲取服務器的響應內容。

6. 釋放連接。無論執行方法是否成功,都必須釋放連接

四、實例

1.創建配置文件src->main->resources->application.properties

test.url=http://localhost:8080

getCookies.uri=/getCookies
test.post.with.cookies=/post/with/cookies

2.創建接口類

package com.course.httpclient.cookies;

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.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

public class MyCookiesForPost {
    private String url;
    private ResourceBundle bundle;

    //用來存儲cookies信息的變量
    private CookieStore store;

    @BeforeTest
    public void beforeTest(){
        bundle = ResourceBundle.getBundle("application",Locale.CHINA);
        url = bundle.getString("test.url");
    }

    @Test
    public void testGetCookies() throws IOException {
        String result;
        //從配置文件中拼接測試的URL
        String uri = bundle.getString("getCookies.uri");
        String testUrl = this.url + uri;

        //測試邏輯代碼書寫
        HttpGet get = new HttpGet(testUrl);
        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(get);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);

        //獲取cookies信息
        this.store = client.getCookieStore();
        List<Cookie> cookiesList = store.getCookies();
        for (Cookie cookie : cookiesList) {
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println("cookie name = "+name +";cookie value = "+value);
        }
    }
    @Test(dependsOnMethods = {"testGetCookies"})
    public void testPostMethod() throws IOException {
        String uri = bundle.getString("test.post.with.cookies");
        //拼接最終的測試地址
        String testUrl = this.url + uri;

        //聲明一個Client對象,用來進行方法的執行
        DefaultHttpClient client = new DefaultHttpClient();

        //聲明一個方法,這個方法就是post方法
        HttpPost post = new HttpPost(testUrl);

        //添加參數
        JSONObject param = new JSONObject();
        param.put("name","huhansan");
        param.put("age","18");

        //設置請求頭信息  設置header
        post.setHeader("content-type","application/json");

        //將參數信息添加到方法中
        StringEntity entity = new StringEntity(param.toString(),"utf-8");
        post.setEntity(entity);

        //聲明一個對象來進行響應結果的存儲
        String result;

        //設置cookies信息
        client.setCookieStore(this.store);
        //執行post方法
        HttpResponse response = client.execute(post);
        //獲取響應結果
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);
        //處理結果,就是判斷結果是否符合預期
        JSONObject resultJson = new JSONObject(result);
        String success = (String) resultJson.get("huhansan");
        String status = (String) resultJson.get("status");
        Assert.assertEquals("success",success);
        Assert.assertEquals("1",status);
    }
}

參考:https://blog.csdn.net/zhuwukai/article/details/78644484

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