JAVA--HttpUtil工具类

本文介绍了一个实用的HttpUtility工具类,用于简化HTTP请求操作,包括GET、POST请求,支持参数传递和JSON数据发送。文章详细展示了如何使用此工具类执行各种HTTP请求,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

添加依赖

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

HttpUtility工具类

public class HttpUtility {
    public static String doGet(String url) {							// 无参数get请求
        return doGet(url, null);
    }

    public static String doGet(String url, Map<String, String> param) {	// 带参数get请求
        CloseableHttpClient httpClient = HttpClients.createDefault();	// 创建一个默认可关闭的Httpclient 对象
        String resultMsg = "";											// 设置返回值
        CloseableHttpResponse response = null;							// 定义HttpResponse 对象
        try {
            URIBuilder builder = new URIBuilder(url);					// 创建URI,可以设置host,设置参数等
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);					// 创建http GET请求
//            httpGet.setHeader(key,value);                     //设置请求的请求头
            response = httpClient.execute(httpGet);						// 执行请求
            if (response.getStatusLine().getStatusCode() == 200) {		// 判断返回状态为200则给返回值赋值
                resultMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {														// 不要忘记关闭
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMsg;
    }

    public static String doPost(String url) {							// 无参数post请求
        return doPost(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {// 带参数post请求
        CloseableHttpClient httpClient = HttpClients.createDefault();	// 创建一个默认可关闭的Httpclient 对象

        CloseableHttpResponse response = null;
        String resultMsg = "";
        try {
            HttpPost httpPost = new HttpPost(url);						// 创建Http Post请求
//            httpPost.setHeader(key,value);                            //设置post请求的请求头
            if (param != null) {										// 创建参数列表
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);// 模拟表单
                httpPost.setEntity(entity);
            }
            response = httpClient.execute(httpPost);					// 执行http请求
            if (response.getStatusLine().getStatusCode() == 200) {
                resultMsg = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMsg;
    }

    public static String doPostJson(String url, String json) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
//            httpPost.setHeader(key,value);                            //设置post请求的请求头
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);     //指定传输参数为json
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
}


HttpClient实现Http请求的步骤如下:

  1. 创建CloseableHttpClient
  2. 创建HttpGet或HttpPost对象,传入url,有参数就传入参数
  3. httpclient执行请求,用HttpResponse接受返回数据
  4. 使用HttpEntity在response中获取entity
  5. 将entity转化成string,再规范成JsonObject
### Java 百度地图 HttpUtil 工具类使用示例 在Java项目中与百度地图API进行交互时,可以利用多种HTTP客户端库来发送请求并处理响应。对于这类操作,`HttpUtils`工具类能够提供便捷的方法来进行网络通信。 #### 使用Apache HttpClient实现百度地图服务调用 当采用Apache HttpClient作为底层传输机制时,可以通过构建GET或POST请求向百度地图Web API发起查询: ```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 BaiduMapClient { private static final String BASE_URL = "https://api.map.baidu.com/"; public String getLocationInfo(String location) throws Exception { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { String url = BASE_URL + "place/v2/search?query=" + location + "&region=北京&output=json&ak=YOUR_API_KEY"; HttpGet httpGet = new HttpGet(url); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { return EntityUtils.toString(response.getEntity()); } } } } ``` 此代码片段展示了如何通过构造特定参数的URL字符串,并借助于`HttpGet`对象执行GET请求获取地理位置信息[^1]。 #### 利用Hutool简化接口调用过程 为了进一步提高开发效率以及增强程序健壮性,推荐引入第三方开源框架——Hutool中的`HttpUtil`组件。该工具不仅支持同步异步两种模式下的数据交换,还内置了丰富的配置选项用于调整超时时间、设置代理服务器等功能特性。 下面是一个基于Hutool `HttpUtil.get()`方法访问百度地图地理编码API的例子: ```java import cn.hutool.http.HttpRequest; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; public class HutoolBaiduMapExample { private static final String GEOCODE_API = "http://api.map.baidu.com/geocoder/v2/"; public JSONObject getGeoCode(String address, String ak){ HttpRequest request = HttpRequest.get(GEOCODE_API) .form("address", address) .form("output","json") .form("ak", ak); String resultStr = request.execute().body(); // 将返回的结果转换成JSON对象以便解析 return JSONUtil.parseObj(resultStr); } } ``` 上述实例说明了怎样运用Hutool提供的静态工厂方法快速建立HTTP GET请求,并且直接接收到了来自远程服务器端口的数据包体内容。随后再经由`cn.hutool.json`包里的辅助函数完成序列化工作,最终得到易于分析的对象结构[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值