当前位置: 首页 > news >正文

搭建一个包含多种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<String,String> params) {
    String result = null;
    try {
        URIBuilder uriBuilder=new URIBuilder(url);
        Iterator maplist=params.entrySet().iterator();
        while (maplist.hasNext()){
            Map.Entry<String,String> map= (Map.Entry<String, String>) 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<String, String> 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<Map.Entry<String, String>> it = map.entrySet().iterator();
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    while (it.hasNext()) {
        Map.Entry<String, String> 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工具类中,以后再用的时候就很方便了。

相关文章:

  • 一致性hash原理与实现
  • 作为一个程序员需要了解多少网络方面的基础?网络基础总结(不断更新)
  • 四千字从源码分析ConcurrentHashMap的底层原理(JDK1.8)
  • redis学习笔记6--集合类型
  • 都2020年了,你还不知道count(1)和count(*)谁效率更高吗?
  • Linux下PF_PACKET的使用,RARP的server和client程序
  • 面试官:不会真有人不知道什么是线程池吧?
  • 从零搭建基于SpringBoot的秒杀系统(一):项目准备
  • 【总结】oracle恢复误删除数据,解除锁定的等sql语句
  • 从零搭建基于SpringBoot的秒杀系统(二):快速搭建一个SpringBoot项目
  • 重拾cgi——cgi dispatcher
  • 从零搭建基于SpringBoot的秒杀系统(三):首页、详情页编写
  • 从零搭建基于SpringBoot的秒杀系统(四):雪花算法生成订单号以及抢购功能实现
  • 操作系统实验一 命令解释程序的编写
  • 从零搭建基于SpringBoot的秒杀系统(五):基于Shiro的人员登陆认证
  • 【159天】尚学堂高琪Java300集视频精华笔记(128)
  • iBatis和MyBatis在使用ResultMap对应关系时的区别
  • JAVA并发编程--1.基础概念
  • js学习笔记
  • k8s如何管理Pod
  • MYSQL 的 IF 函数
  • mysql常用命令汇总
  • PHP变量
  • react 代码优化(一) ——事件处理
  • Spring Cloud Alibaba迁移指南(一):一行代码从 Hystrix 迁移到 Sentinel
  • 从零到一:用Phaser.js写意地开发小游戏(Chapter 3 - 加载游戏资源)
  • 动手做个聊天室,前端工程师百无聊赖的人生
  • 二维平面内的碰撞检测【一】
  • 番外篇1:在Windows环境下安装JDK
  • 极限编程 (Extreme Programming) - 发布计划 (Release Planning)
  • 简单基于spring的redis配置(单机和集群模式)
  • 力扣(LeetCode)965
  • 配置 PM2 实现代码自动发布
  • 微信如何实现自动跳转到用其他浏览器打开指定页面下载APP
  • 限制Java线程池运行线程以及等待线程数量的策略
  • 用element的upload组件实现多图片上传和压缩
  • 职业生涯 一个六年开发经验的女程序员的心声。
  • nb
  • Oracle Portal 11g Diagnostics using Remote Diagnostic Agent (RDA) [ID 1059805.
  • 没有任何编程基础可以直接学习python语言吗?学会后能够做什么? ...
  • #、%和$符号在OGNL表达式中经常出现
  • #define MODIFY_REG(REG, CLEARMASK, SETMASK)
  • #HarmonyOS:基础语法
  • #NOIP 2014# day.2 T2 寻找道路
  • ( )的作用是将计算机中的信息传送给用户,计算机应用基础 吉大15春学期《计算机应用基础》在线作业二及答案...
  • (BFS)hdoj2377-Bus Pass
  • (WSI分类)WSI分类文献小综述 2024
  • (每日持续更新)信息系统项目管理(第四版)(高级项目管理)考试重点整理 第13章 项目资源管理(七)
  • (转)http协议
  • (转)IIS6 ASP 0251超过响应缓冲区限制错误的解决方法
  • . NET自动找可写目录
  • .Mobi域名介绍
  • .NET NPOI导出Excel详解
  • .net 反编译_.net反编译的相关问题
  • .net 后台导出excel ,word