HttpClientUtil

该博客介绍了如何使用Apache HttpClient库实现HTTP POST和GET请求。内容包括创建HttpClient对象,设置请求头,处理POST数据,以及获取和解析响应内容的方法。此外,还提供了RESTful风格的GET请求实现。
package com.lemon.move.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

@Slf4j
public class HttpClientUtil {

    /**
     * post请求
     *
     * @param url     路径
     * @param data    数据
     * @param charset 字符格式,例:UTF-8
     * @param map     请求头参数信息
     * @return 返回字符串格式
     */
    public static String httpPostSend(String url, String data, String charset, Map<String, Object> map) {
        String body = "";
        try {
            JSONObject jsonObject = JSON.parseObject(data);
            //创建httpclient对象
            CloseableHttpClient client = HttpClients.createDefault();
            //创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json; charset=UTF-8");
            //装填参数
            StringEntity s = new StringEntity(jsonObject.toJSONString(), charset);
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");/*
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json;charset=UTF-8"));*/
            //设置参数到请求对象中
            httpPost.setEntity(s);
            if (map != null && map.size() > 0) {
                for (String key : map.keySet()) {
                    if (!"data".equals(key)) {
                        httpPost.setHeader(key, map.get(key) + "");
                    }
                }
            }
            //设置header信息
            //指定报文头【Content-type】、【User-Agent】
            // 浏览器表示
            //执行请求操作,并拿到结果(同步阻塞)
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, charset);
                log.info("按指定编码转换结果实体为String类型: " + body);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return body;
    }

    /**
     * restful 风格,如果需要使用默认的风格的话可以对urlNameString 拼接时修改
     * @param urlStr   请求的地址
     * @param content  请求的参数 格式为:name=xxx&pwd=xxx
     * @param encoding 服务器端请求编码。如GBK,UTF-8等
     * @return 返回字符串类型
     */
    public static String httpGetSend(String urlStr, String content, String encoding) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = urlStr + URLEncoder.encode(content, encoding);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), encoding));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.info("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

}


### HttpClientUtil 类使用示例 #### 工具类概述 `HttpClientUtils` 是一个封装了常用 HTTP 请求操作的工具类,基于 Apache HttpClient 实现。该工具类支持 GET、POST、PUT、DELETE 等常见的请求方法,并提供了请求头设置、参数传递、响应处理以及超时设置等功能[^1]。 #### Maven依赖配置 为了使用 `HttpClientUtils` 或者直接使用 Apache HttpClient 进行开发,项目中需要引入相应的 Maven 依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.13</version> </dependency> ``` #### 发送GET请求实例 下面是一个简单的发送 GET 请求并打印服务器返回内容的例子: ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpGet request = new HttpGet("https://jsonplaceholder.typicode.com/posts/1"); // 执行GET请求 CloseableHttpResponse response = httpClient.execute(request); try { System.out.println(EntityUtils.toString(response.getEntity())); } finally { response.close(); } } finally { httpClient.close(); } } } ``` 此代码创建了一个默认的 `CloseableHttpClient` 对象来执行 HTTP 请求。通过构建 `HttpGet` 来指定目标 URL 并调用 `execute()` 方法发起请求。最后读取响应实体的内容并通过 `EntityUtils.toString()` 转换成字符串形式输出到控制台[^4]。 对于更复杂的场景,比如 POST 表单提交或者上传文件,则可以通过调整上述模板中的具体实现细节完成相应功能需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lemon20120331

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值