欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

接口自动化测试第三篇 HTTPClient

程序员文章站 2022-06-24 23:54:31
...

使用方法:

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
1. 创建HttpClient对象。
2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
6. 释放连接。无论执行方法是否成功,都必须释放连接

Maven pom.xml导入httpclient依赖

 <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

代码:

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    public static String get(String url){
        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        try {
            httpClient = HttpClients.createDefault();
            //请求配置
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000)
                    .setConnectTimeout(20000)
                    .build();
            //创建HttpGet实例
            httpGet = new HttpGet(url);
            //对HttpGet指定配置
            httpGet.setConfig(requestConfig);
            //启动httpget请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String reponseInformation = EntityUtils.toString(entity,"UTF-8");
            return reponseInformation;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (httpGet != null) {
                    httpGet.releaseConnection();
                }

                if (httpClient != null ) {
                    httpClient.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    /*
    * HTTPCLIENT-POST请求:x-www-form-urlencoded  类型
    *
    * */
    public static String post(String url, Map<String,String> params){
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        try {
            httpClient = HttpClients.createDefault();
            //请求配置
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000)
                    .setConnectTimeout(20000)
                    .build();
            //创建HttpPost实例
            httpPost = new HttpPost(url);
            //对HttpPost指定配置
            httpPost.setConfig(requestConfig);
            List<NameValuePair> ps = new ArrayList<>();
            for (String key : params.keySet()) {
                NameValuePair nv = new BasicNameValuePair(key,params.get(key));
                ps.add(nv);
            }
            UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(ps);
            httpPost.setEntity(requestEntity);
            //启动httpPost请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String reponseInformation = EntityUtils.toString(entity,"UTF-8");
            return reponseInformation;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (httpPost != null) {
                    httpPost.releaseConnection();
                }

                if (httpClient != null ) {
                    httpClient.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }
    /*
     * HTTPCLIENT-POST请求:APPLICATION_JSON类型数据
     *
     * */
    public static String post(String url, String body){
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        try {
            httpClient = HttpClients.createDefault();
            //请求配置
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000)
                    .setConnectTimeout(20000)
                    .build();
            //创建HttpPost实例
            httpPost = new HttpPost(url);
            //对HttpPost指定配置
            httpPost.setConfig(requestConfig);
//            List<NameValuePair> ps = new ArrayList<>();
//            for (String key : params.keySet()) {
//                NameValuePair nv = new BasicNameValuePair(key,params.get(key));
//                ps.add(nv);
//            }
            //闯入的参数,传入的参数类型为"APPLICATION_JSON"
            StringEntity requestEntity = new StringEntity(body,ContentType.APPLICATION_JSON);
            httpPost.setEntity(requestEntity);
            //启动httpPost请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String reponseInformation = EntityUtils.toString(entity,"UTF-8");
            return reponseInformation;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (httpPost != null) {
                    httpPost.releaseConnection();
                }

                if (httpClient != null ) {
                    httpClient.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }
    public static void main (String [] args){
//        //GET请求
//        String s = get("http://v.juhe.cn/weather/index?format=2&cityname=北京&key=9679a0703822fe67b9cff961ba197b02");
//        System.out.println(s);

        //POST请求
        Map<String,String> map = new HashMap<>();
        map.put("subject","4");
        map.put("model","a1");
        map.put("testType","order");
        map.put("key","5d5d6091ba01de0c27e84b4ab2fca5df");
        String s1=post("http://v.juhe.cn/jztk/query",map);
        System.out.println(s1);

        String s2=post("http://v.juhe.cn/wepiao/query","{\"key\":\"24f59d857d2ad45011946fede9ae5d55\"}");
        System.out.println(s2);

    }
}

相关标签: httpclient