http请求工具类

Http请求工具类

一、使用现成的工具类:HuTool

链接:Hutool官网

依赖:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.22</version>
</dependency>

二、使用自己封装的工具类

依赖:

 <!-- gson -->
<dependency>
     <groupId>com.google.code.gson</groupId>
     <artifactId>gson</artifactId>
     <version>2.6</version>
</dependency>

<!-- http client -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.9</version>
</dependency>

代码:

public class HttpUtils {
    /**
     * 带参数的get请求
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static String doGet(String url, Map<String, Object> map)
            throws Exception {
        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);
        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue()
                        .toString());
            }
        }
        // 2 创建httpGet对象,相当于设置url请求地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        return sendHttpReq(httpGet);
    }

    /**
     * 不带参数的get请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String doGet(String url) throws Exception {
        return doGet(url,null);
    }

    /**
     * 带参数的post请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String doPost(String url, Map<String, Object> reqMap,
                                Map<String, String> headersMap) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        for (Map.Entry<String, String> entry : headersMap.entrySet())
            httpPost.addHeader(entry.getKey(), entry.getValue());
        // 判断map不为空
        if (reqMap != null) {
            Gson gson = new GsonBuilder().create();
            // 创建form表单对象
            StringEntity formEntity = new StringEntity(gson.toJson(reqMap),
                    "UTF-8");
            // 把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);
        }
        return sendHttpReq(httpPost);
    }

    private static String sendHttpReq(HttpUriRequest method) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;

        try {
            httpClient = HttpClients.createDefault();
            response = httpClient.execute(method);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception var14) {
            throw new RuntimeException(var14);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException var13) {
                var13.printStackTrace();
            }
        }
        return responseContent;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中有多种HTTP请求工具类可供使用,其中一种是http-request。它基于URLConnection实现,不依赖于HttpClient。使用http-request发送GET请求示例如下: 1. 引入依赖: ``` <dependency> <groupId>com.github.kevinsawicki</groupId> <artifactId>http-request</artifactId> <version>5.6</version> </dependency> ``` 2. 发送GET请求获取响应报文: ```java String response = HttpRequest.get("http://www.baidu.com").body(); System.out.println("Response was: " + response); ``` 3. 发送GET请求获取响应码: ```java int code = HttpRequest.get("http://google.com").code(); ``` 除了http-request,还有其他一些常用的HTTP请求工具类,比如HttpUtil。使用HttpUtil发送GET请求的示例代码如下: ```java // 最简单的HTTP请求,自动判断编码 String result1 = HttpUtil.get("https://www.baidu.com"); // 自定义请求页面的编码 String result2 = HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8); // 传入http参数,参数会自动做URL编码,拼接在URL中 HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result3 = HttpUtil.get("https://www.baidu.com", paramMap); ``` 如果需要发送POST请求,可以使用HttpUtil的post方法,示例代码如下: ```java HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result = HttpUtil.post("https://www.baidu.com", paramMap); ``` 另外,如果需要文件上传,可以将参数中的键指定为"file",值设为文件对象即可,示例代码如下: ```java HashMap<String, Object> paramMap = new HashMap<>();paramMap.put("file", FileUtil.file("D:\\face.jpg")); String result = HttpUtil.post("https://www.baidu.com", paramMap); ``` 以上是一些常用的Java HTTP请求工具类,你可以根据具体需求选择适合的工具类来发送HTTP请求。请问您还有其他相关问题吗? 相关问题: 1. Java中还有哪些常用的HTTP请求工具类? 2. 如何处理HTTP请求的返回结果? 3. 如何设置HTTP请求的超时时间?

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值