HttpClient接口测试之会话保持
HttpClient4.X自带会话保持功能,使用同一个HttpClient未关闭的连接即可保持登陆会话,如果多个HttpClient想要使用一个登陆会话,则需要保存会话信息,其中一种方法是使用HttpClientContext。
import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.junit.Test; import com.test.tools.Regular; public class HttpClientTest { String loginUrl = "http://**.***.com/user/login.do"; private static HttpContext localContext = new BasicHttpContext(); private static HttpClientContext context = HttpClientContext.adapt(localContext); @Test public void Test() throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); try { // 模拟表单 List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", "admin")); params.add(new BasicNameValuePair("password", "admin")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); HttpPost httpPost = new HttpPost(loginUrl); httpPost.setEntity(entity); // 将HttpClientContext传入execute()中 CloseableHttpResponse response = httpClient.execute(httpPost, context); try { HttpEntity responseEntity = response.getEntity(); System.out.println(EntityUtils.toString(responseEntity)); } finally { response.close(); } } finally { httpClient.close(); } CloseableHttpClient httpClient2 = HttpClients.createDefault(); try { //进入首页 HttpGet httpGet = new HttpGet("http://**.***.com/front/investmentList.html"); // 设置相同的HttpClientContext CloseableHttpResponse response = httpClient2.execute(httpGet, context); try { HttpEntity entity = response.getEntity(); System.out.println("**************************"); String aString =EntityUtils.toString(entity); System.out.println(aString); //正则提取响应信息中的用户名 String bsString = "loginName = "(.+?)""; Regular regular = new Regular(); System.out.println(regular.getRegular(aString, bsString)); } finally { response.close(); } } finally { httpClient2.close(); } } } |
通过这种方式可以进行接口测试,也可以加入断言事务,添加多线程并发进行接口性能测试。