搭建一个包含多种Get请求和Post请求的工具类

简介: 在工作的过程中经常会遇到需要调用接口的场景,用得多了就写了一个请求的工具类,以后再遇到需要Get请求或者Post请求的情况直接调用就行。

Get请求不带参数

传入的数据是个Url,如果有需要可以添加其他header信息,返回String类型的返回值。


/***
 * get请求
 * @param url
 * @return String
 */
public static String doGet(String url) {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpGet get = new HttpGet(url);
    String result = null;
    try {
        get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        HttpResponse response = client.execute(get);
        result = EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

Get请求带参数

Get请求的参数会附带在链接的后面,这里传入的参数是url和hashmap键值对,如果有需要可以添加其他header信息,返回String类型的返回值。


/***
 * get请求(带参数)
 * @param url
 * @return String
 */
public static String doGet(String url,HashMap params) {
    String result = null;
    try {
        URIBuilder uriBuilder=new URIBuilder(url);
        Iterator maplist=params.entrySet().iterator();
        while (maplist.hasNext()){
            Map.Entry map= (Map.Entry) maplist.next();
            uriBuilder.addParameter(map.getKey(),map.getValue());
        }
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(uriBuilder.build()); get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        HttpResponse response = client.execute(get);
        result = EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}


Post请求(JSON格式的参数)

传入的参数是String类型的url和params参数,params参数需要的是json对象转换后的String字符串


/**
 * post 请求(用于请求 json 格式的参数)
 * @param url
 * @param params
 * @return
 */
public static String doPost(String url, String params) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);// 创建 httpPost
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-Type", "application/json");
    String charSet = "UTF-8";
    StringEntity entity = new StringEntity(params, charSet);
    httpPost.setEntity(entity);
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpPost);
        StatusLine status = response.getStatusLine();
        int state = status.getStatusCode();
        if (state == HttpStatus.SC_OK) {
            HttpEntity responseEntity = response.getEntity();
            String jsonString = EntityUtils.toString(responseEntity);
            return jsonString;
        }
        else{
        } }
    finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            } }
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        } }
    return null;
}


Post请求(form格式的参数)

请求的参数是String类型的url和Hashmap键值对,键值对中存放from的键和值


/***
 * post请求(用于处理form格式的数据)
 * @param url
 * @param map
 * @return
 * @throws Exception
 */
public static String doPost(String url, HashMap map) throws Exception {
    String result = "";
    CloseableHttpClient client = null;
    CloseableHttpResponse response = null;
    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000)
            .setConnectionRequestTimeout(550000).build();
    client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    // client = HttpClients.createDefault();
    URIBuilder uriBuilder = new URIBuilder(url);
    HttpPost httpPost = new HttpPost(uriBuilder.build());
    httpPost.setHeader("Connection", "Keep-Alive");
    httpPost.setHeader("Charset", CHARSET_UTF8);
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    Iterator> it = map.entrySet().iterator();
    List params = new ArrayList();
    while (it.hasNext()) {
        Map.Entry entry = it.next();
        NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
        params.add(pair);
    }
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    try {
        response = client.execute(httpPost);
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, CHARSET_UTF8);
            }
        }
    } catch (ClientProtocolException e) {
        throw new RuntimeException("创建连接失败" + e);
    } catch (IOException e) {
        throw new RuntimeException("创建连接失败" + e);
    }
    return result;
}

总结

可以把上面的四个方法封装到自己的NetUtil工具类中,以后再用的时候就很方便了。


相关文章
|
11月前
|
Java
你还不知道怎么用Java代码实现发送post请求、get请求吗?
你还不知道怎么用Java代码实现发送post请求、get请求吗?
|
3月前
|
JavaScript 前端开发 数据格式
URL编码【详解】——Javascript对URL进行编码解码的三种方式的区别和使用场景,axios请求拦截器中对get请求的参数全部进行URL编码
URL编码【详解】——Javascript对URL进行编码解码的三种方式的区别和使用场景,axios请求拦截器中对get请求的参数全部进行URL编码
93 0
|
5月前
|
JSON 数据格式
糊涂工具类(hutool)post请求设置body参数为json数据
糊涂工具类(hutool)post请求设置body参数为json数据
|
5月前
|
缓存 安全 API
Post请求和get请求的区别是什么?
Post请求和get请求的区别是什么?
106 2
|
安全 前端开发 JavaScript
【GET请求和POST请求区别。】
GET请求和POST请求是HTTP协议中最常见的两种请求方法,它们在客户端向服务器发送请求时有着不同的特点和用途。
106 0
|
XML 前端开发 JavaScript
教你怎么用最原始的ajax发送post请求和get请求
教你怎么用最原始的ajax发送post请求和get请求
365 0
|
Web App开发 网络协议 安全
GET和POST方式请求API接口数据返回
GET和POST方式请求API接口数据返回
153 0
|
XML JSON 安全
get请求和post请求的区别以及常用请求方式
get请求和post请求的区别以及常用请求方式
|
数据采集 Python
爬虫第二次笔记 解编码 使用get请求方式和post请求方式
爬虫第二次笔记 解编码 使用get请求方式和post请求方式
245 0
爬虫第二次笔记 解编码 使用get请求方式和post请求方式
|
Web App开发 缓存 安全
get请求和post请求的区别
get请求和post请求的区别
get请求和post请求的区别