接口自動化第一個get請求(從resource裏面讀取配置文件)

httpclient的官網:http://hc.apache.org/httpclient-3.x/performance.html#Cookie_processing

1.在maven工程裏面引入包,

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

2.代碼如下

package com.course.httpclient.cookies;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

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

public class CookiesforGet {
    private String url;
    private ResourceBundle bundle;
    @BeforeClass
    public void beforeTest(){
        //ResourceBundle.getBundle讀取resourse的配置文件
        bundle=ResourceBundle.getBundle("application", Locale.CHINA);
        url=bundle.getString("test.url");
        System.out.println(url);
    }
    @Test
    public void testGetCookies() throws IOException {
        String result=null;
        //創建其中一個方法的實例(在本例中爲GetMethod)。要連接的URL將傳遞給方法構造函數。
        HttpGet get= new HttpGet(this.url+bundle.getString("getCookies.uri"));
        //實例化httpclient,httpclient沒有獲取響應cookies的方法
        HttpClient client=new DefaultHttpClient();
        //告訴HttpClient執行方法。
        HttpResponse response=client.execute(get);
        //取得相應結果
        result= EntityUtils.toString(response.getEntity(),"utf-8");
        String getCookies=response.getLocale().toString();

        System.out.println(result+getCookies);

    }
}

3.配置resourses文件的文件名必須以properties結尾

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