HttpClient学习笔记(配置全局变量)

1.新建application.properties全局变量配置文件

/src/mian/resources目录下,新建application.properties文件,文件内配置访问接口的url和路径

test.url=http://localhost:8899
getCookies.uri=/getcookies

2.引用url

/src/mian/java/com.course.httpclient下新建文件cookies,然后文件内新建一个类:MyCookiesForGet,先从application文件中获取url的地址

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

此时,url获取到了”http://localhost:8899“的值

3.拼接url

用同样的方法,申明一个uri变量,获取”/getcookies”,然后进行拼接

String uri = bundle.getString("getCookies.uri");
String testUrl = this.url+uri;

此时,testUrl获取到了”http://localhost:8899/getcookies“的值

4.使用get方法访问testUrl

String result;
HttpGet get = new HttpGet(testUrl);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);

此前我已经创建出mock接口,这里可以直接进行调用,mock接口的具体创建方法可参考这里

打印结果

到这里,读取mock接口并访问通过全局变量配置的url然后读取信息的操作就成功了


MyCookiesForGet文件完整代码如下:

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

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

public class MyCookiesForGet {

    private String url;
    private ResourceBundle bundle;

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

    @Test
    public void testGetCookies() throws IOException {
        String result;
        String uri = bundle.getString("getCookies.uri");
        String testUrl = this.url+uri;
        HttpGet get = new HttpGet(testUrl);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(get);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);
    }
}

猜你喜欢

转载自blog.csdn.net/lt326030434/article/details/80439559
今日推荐