HttpClient+ ResourceBundle接口配置优化

本文主要包含HttpClient接口测试,ResourceBundle读取配置文件中的接口地址信息。

ResourceBundle可读取.properties文件,.properties的格式是key value。.properties可以配置接口请求中的域名(ip)和路径等信息。.properties应该存放src->main->resources中。

如果.properties文件和java类在同一路径下,那么可以直接用ResourceBundle.getBundle("application", Locale.CHINA)读取文件信息,其中application是文件名。

下面代码包含了java接口测试运行代码 、application.properties配置文件 、moco模拟的get请求json文件。

java代码如下

 1 package com.course.httpclient.cookies;
 2 
 3 import org.apache.http.HttpResponse;
 4 import org.apache.http.client.HttpClient;
 5 import org.apache.http.client.methods.HttpGet;
 6 import org.apache.http.impl.client.DefaultHttpClient;
 7 import org.apache.http.util.EntityUtils;
 8 import org.testng.annotations.BeforeTest;
 9 import org.testng.annotations.Test;
10 
11 import java.io.IOException;
12 import java.util.Locale;
13 import java.util.ResourceBundle;
14 
15 public class MyCookieForGet {
16 
17     private String url;
18     private ResourceBundle bundle;//用于读取配置文件
19 
20     @BeforeTest
21     public void beforeTest() {
22 
23         bundle = ResourceBundle.getBundle("application", Locale.CHINA);
24         //上行代码用于读取配置文件,baseName和类在同一目录的resource文件中
25         url = bundle.getString("test.url");
26         //上行代码是获取配置文件中的域名
27     }
28 
29     @Test
30     public void test1() throws IOException {
31 
32         String result;
33         String uri = bundle.getString("getCookies.uri");
34         //以上代码是获取配置文件中的getCookies.uri对应的路径
35         String testurl = this.url + uri;
36         HttpGet get = new HttpGet(testurl);
37         System.out.println("这是testurl的地址" + testurl);
38         HttpClient client = new DefaultHttpClient();
39         //创建HttpClient对象,用于执行get请求
40         HttpResponse response = client.execute(get);
41         System.out.println("这是response的值" + response);
42 
43         result = EntityUtils.toString(response.getEntity(), "utf-8");
44         System.out.println(result);
45 
46 
47     }
48 
49 }

application.properties配置文件

test.url=http://127.0.0.1:8888
getCookies.uri=/getCookies
login=/login

moco模拟的get请求json文件

 1 [
 2   {
 3     "description": "这是一个会返回cookies信息的get请求",
 4     "request": {
 5       "uri": "/getCookies",
 6       "method": "get"
 7     },
 8     "response": {
 9       "headers": {
10         "Content-Type": "text/html;charset=gbk"
11       },
12       "cookies": {
13         "login": "111111",
14         "status": "1000"
15 
16       },
17       "text": "恭喜你获得cookies信息成功"
18     }
19   }
20 ]

运行结果

 

posted @ 2020-04-01 19:06  小白测试  阅读(262)  评论(0编辑  收藏  举报