测试框架httpclent 2.配置优化方法

      优化就是为了使代码看起来更简便,如果代码里面的每一个请求都写一次url,那么整体代码看起来很乱,而且一旦某个服务器的端口号或者域名有变动,那么所有的url都需要改变,成本太大。为了让代码看起来更简便,修改起来更容易,所以要用配置文件去写url。如果想切换测试环境,代码只需要变动一行就可以。

      所以,在resourse里面新建一个文件,application.properties。后缀名字是properties,里面的内容是key = value ,而且key和value都不需要加引号

test.url = http://localhost:8888
dev.url = http://localhost:8888

getCookies.uri = /getCookies
login = /login

新建一个类:

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;
// 这个工具类就是为了读取properties这样的配置文件的
private ResourceBundle bundle; @BeforeTest public void beforeTest(){
     //获取的文件里面的内容,只需要写文件名字就行,不需要写后缀 bundle
= ResourceBundle.getBundle("application",Locale.CHINA);
     //获取到属性 test.url,获取到这个属性以后,配置文件中的test.url自动变成了非灰色 url
= bundle.getString("test.url");       
}
    @Test
    public void testGetGookies() throws IOException {
      //这个还是上节课的内容 String result; String uri
= bundle.getString("getCookies.uri"); HttpGet get = new HttpGet(this.url + uri); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); result = EntityUtils.toString(response.getEntity(),"utf-8"); System.out.println(result); } }

猜你喜欢

转载自www.cnblogs.com/peiminer/p/9662648.html