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


相关文章
|
Prometheus 监控 Cloud Native
【监控】prometheus传统环境监控告警常用配置
【监控】prometheus传统环境监控告警常用配置
【监控】prometheus传统环境监控告警常用配置
|
设计模式 容器
如何理解IOC中的反射操作
如何理解IOC中的反射操作
|
存储 Shell Linux
【Shell 命令集合 系统设置 内建命令】⭐Linux 声明变量的属性和类型 declare命令 使用指南
【Shell 命令集合 系统设置 内建命令】⭐Linux 声明变量的属性和类型 declare命令 使用指南
230 0
|
XML 开发框架 安全
WebShell 特征分析
`WebShell`是黑客经常使用的一种恶意脚本,其目的是获得服务器的执行操作权限,常见的webshell编写语言为`asp `/`jsp`/`php`。主要用于网站管理,服务器管理,权限管理等操作。使用方法简单,只需要上传一个代码文件,通过网址访问,便可进行很多日常操作,极大地方便了使用者对网站的服务器的管理。
716 0
|
SQL 分布式计算 Hadoop
在文件存储HDFS版上使用 Presto
本文档主要介绍在文件存储HDFS版上搭建及使用 Presto。
773 0
|
前端开发 JavaScript
前端学习:javascript基本知识
前端学习:javascript基本知识
183 0
前端学习:javascript基本知识
|
存储 前端开发 JavaScript
JavaScript进阶之继承
JavaScript进阶之继承
123 0
JavaScript进阶之继承
屏蔽Windows98/2000/XP任务栏、win键、Ctrl+Esc、Alt+Tab等
关于这方面的文章挺多,对任务栏、win键、Ctrl+Esc、Alt+Tab的屏蔽,一般方法较为简单,最多用底层键盘钩子+DLL就能完美解决
4267 0