java httpclient接口自动化
环境准备:
idea 在pom文件中引入依赖包
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.4</version> </dependency>
先初始化一些参数和实例
String url; //请求地址 CloseableHttpClient httpClient; //用来发送http请求的HttpClient实例 CloseableHttpResponse httpResponse; //用来接受响应信息的实例 String responseBody; //存储响应主体
创建get请求:
//创建一个httpClient的实例 httpClient = HttpClients.createDefault(); //创建一个httpGet请求实例 HttpGet httpGet = new HttpGet(url); //使用httpClient实例发送刚创建的get请求,并用httpResponse将反馈接收 httpResponse = httpClient.execute(httpGet);
//处理响应
HttpEntity entity = httpResponse.getEntity();
responseBody = EntityUtils.toString(entity,"tuf-8");
创建post请求:
//创建一个httpClient的实例 httpClient = HttpClients.createDefault(); //创建一个httpGet请求实例 HttpPost httpPost = new HttpPost(url); //添加参数params Map<String, String> params = new HashMap<String, String>(); params.put("username","ceshi1"); params.put("password","123456"); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //创建参数队列 for (Map.Entry<String, String> entry : params.entrySet()) { formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } post.setEntity(new UrlEncodedFormEntity(formParams, "utf-8")); //使用httpClient实例发送刚创建的get请求,并用httpResponse将反馈接收 httpResponse = httpClient.execute(httpPost); //处理响应 HttpEntity entity = httpResponse.getEntity(); responseBody = EntityUtils.toString(entity,"utf-8");