Java测试开发--HttpClient常规用法(九)

1.HttpClient可以读取网页(HTTP/HTTPS)内容

2.对url发送get/post请求(带不带参数都可以),进行测试

一、maven项目pom.xml需要引入包

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

二、新建类进行测试

 1 public class HttpClientTest {
 2     
 3     public static void main(String[] args) throws IOException{
 4         //创建默认http请求
 5         HttpClient  httpClient = HttpClients.createDefault();
 6         //创建post请求
 7         HttpPost  httpPost = new HttpPost("http://127.0.1.1:8080/goods/UserServlet");
 8         //传递参数
 9         List<NameValuePair> pairsList = new ArrayList<NameValuePair>();
10         
11         BasicNameValuePair bPair1 = new BasicNameValuePair("method", "loginMobile");
12         BasicNameValuePair bPair2 = new BasicNameValuePair("loginname", "abc");
13         BasicNameValuePair bPair3 = new BasicNameValuePair("password", "abc");
14         pairsList.add(bPair1);
15         pairsList.add(bPair2);
16         pairsList.add(bPair3);
17         HttpEntity httpEntity = null;
18         try {
19             //参数转码
20             httpEntity = new UrlEncodedFormEntity(pairsList,"utf-8");
21             //请求实体放入post请求中
22             httpPost.setEntity(httpEntity);
23             //用http连接执行post请求并且获得http请求响应
24             HttpResponse response = httpClient.execute(httpPost);
25             //从response中取到响应实体
26             HttpEntity entity = response.getEntity();
27             //把响应实体转到文本
28             String  html = EntityUtils.toString(entity);
29             System.out.println("====="+html);
30         } catch (UnsupportedEncodingException e) {
31             // TODO Auto-generated catch block
32             e.printStackTrace();
33         }
34     }
35 
36 }

 

posted @ 2021-08-26 15:55  胖儿1018  阅读(126)  评论(0编辑  收藏  举报