搭建一个包含多种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工具类中,以后再用的时候就很方便了。


相关文章
|
存储 消息中间件 NoSQL
redis入门到精通系列(一):入门redis看这一篇就够了
如果你是计算机专业学生 ,那么一定使用过关系型数据库mysql。在请求量小的情况下,使用mysql不会有任何问题,但是一旦同时有成千上万个请求同时来访问系统时,就会出现卡顿甚至系统崩溃的情况。最典型的例子就是早期的12306购票网站,一旦到了购票高峰期,12306肯定崩溃。造成这个原因的罪魁祸首就是关系型数据库。
7371 0
redis入门到精通系列(一):入门redis看这一篇就够了
MapStruct - 生成空对象解决方案
MapStruct - 生成空对象解决方案
1808 0
|
前端开发 网络协议 Dubbo
超详细Netty入门,看这篇就够了!
本文主要讲述Netty框架的一些特性以及重要组件,希望看完之后能对Netty框架有一个比较直观的感受,希望能帮助读者快速入门Netty,减少一些弯路。
91263 32
超详细Netty入门,看这篇就够了!
|
Prometheus 监控 Cloud Native
【监控】prometheus传统环境监控告警常用配置
【监控】prometheus传统环境监控告警常用配置
【监控】prometheus传统环境监控告警常用配置
|
设计模式 容器
如何理解IOC中的反射操作
如何理解IOC中的反射操作
|
SQL Arthas 运维
取经阿里十年技术大佬,得到Java线上问题排查攻略!
再牛逼的程序员都写不出完美无缺的代码,作为后端开发工程师,一不小心就会遇到线上故障。如果线上故障处理不及时,就可能导致各种严重的后果。恰好最近部门出现了一次挺严重但幸运的是影响面不大的线上故障,最后在阿里工作十年的leader分享了线上问题的排查思路。结合这次分享,写下了这篇Java线上问题排查攻略。
|
JSON NoSQL 安全
redis入门到精通系列(十):springboot快速集成redis
在前面的博客系列中,我们把redis的基础语法配置等比较详细的讲了一遍,但如果要用现在更多的是集成到spring系列的框架之中,今天我们就来讲解springboot集成redis的方法以及一些注意点。
1006 0
如何用Java写一个规范的http接口?
在平常的工作中,经常会遇到要写接口的情况,现在最常用的就是http接口,今天我就介绍一下如何去写一个规范的http接口。
|
Java Maven
Maven下载,本地仓库,远程仓库配置
Maven下载,本地仓库,远程仓库配置
480 0
|
缓存 算法 安全
基于知识图谱(Knowledge Graph)的学习类软件
基于知识图谱(Knowledge Graph)的学习类软件
406 0