HttpUtils工具类

HttpUtils工具类

  • 常见的几种请求方式
    • httpcomponent
    • resttemplate
    • okhhttp3
import com.ectrip.b2b.common.log.ExceptionLog;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.IOException;
import java.util.Map;
public class HttpUtils {

    /** Http默认交互编码 */
    private static final String DEFAULT_CHARSET = "UTF-8";

    /** Http默认连接超时时间 */
    private static final int DEFAULT_CONNECTION_TIMEOUT = 30000;

    private static final int DEFAULT_SOCKET_TIMEOUT = 60000;


    public static String doGet(String apiUrl) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpGet httpGet = new HttpGet(apiUrl);
        CloseableHttpResponse response = null;

        try {
            // 设置请求超时时间
            RequestConfig requestConfig = RequestConfig
                    .custom()
                    .setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT)
                    .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                    .build();
            httpGet.setConfig(requestConfig);

            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            ExceptionLog.print(e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    ExceptionLog.print(e.getMessage(), e);
                }
            }
            try {
                if (httpClient != null) httpClient.close();
            } catch (IOException e) {
                ExceptionLog.print(e.getMessage(), e);
            }
        }
        return httpStr;
    }

    public static String doGet(String apiUrl, Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpGet httpGet = new HttpGet(apiUrl);
        CloseableHttpResponse response = null;

        try {
            // 设置自定义header
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
            }
            // 设置请求超时时间
            RequestConfig requestConfig = RequestConfig
                    .custom()
                    .setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT)
                    .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                    .build();
            httpGet.setConfig(requestConfig);

            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            ExceptionLog.print(e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    ExceptionLog.print(e.getMessage(), e);
                }
            }
            try {
                if (httpClient != null) httpClient.close();
            } catch (IOException e) {
                ExceptionLog.print(e.getMessage(), e);
            }
        }
        return httpStr;
    }

    public static String doPostJson(String apiUrl, String json) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;

        try {
            //设置请求超时时间
            RequestConfig requestConfig = RequestConfig
                    .custom()
                    .setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT)
                    .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                    .build();
            httpPost.setConfig(requestConfig);
            //解决中文乱码问题
            StringEntity stringEntity = new StringEntity(json, "UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            ExceptionLog.print(e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    ExceptionLog.print(e.getMessage(), e);
                }
            }
            try {
                if (httpClient != null) httpClient.close();
            } catch (IOException e) {
                ExceptionLog.print(e.getMessage(), e);
            }
        }
        return httpStr;
    }


    public static String doPostJson(String apiUrl, String json,  Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;

        try {
            // 设置自定义header
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            //设置请求超时时间
            RequestConfig requestConfig = RequestConfig
                    .custom()
                    .setConnectionRequestTimeout(DEFAULT_CONNECTION_TIMEOUT)
                    .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
                    .build();
            httpPost.setConfig(requestConfig);
            //解决中文乱码问题
            StringEntity stringEntity = new StringEntity(json, "UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            httpStr = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            ExceptionLog.print(e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    ExceptionLog.print(e.getMessage(), e);
                }
            }
            try {
                if (httpClient != null) httpClient.close();
            } catch (IOException e) {
                ExceptionLog.print(e.getMessage(), e);
            }
        }
        return httpStr;
    }


}

### JavaHttpUtils 工具类的使用方法 #### 构建 URL 的方法 `buildUrl` 方法用于构建完整的 URL 请求地址。该方法接收主机名 (`host`)、路径 (`path`) 和查询参数 (`querys`) 并将其编码为合法的 URL 字符串。 以下是 `buildUrl` 方法的一个实现示例: ```java import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Map; public class HttpUtils { private static String buildUrl(String host, String path, Map<String, Object> querys) throws Exception { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(host).append(path); if (querys != null && !querys.isEmpty()) { boolean first = true; for (Map.Entry<String, Object> entry : querys.entrySet()) { if (first) { urlBuilder.append("?"); first = false; } else { urlBuilder.append("&"); } urlBuilder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString())); urlBuilder.append("="); urlBuilder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8.toString())); } } return urlBuilder.toString(); } } ``` 此代码片段展示了如何通过拼接字符串并对其进行 UTF-8 编码来创建一个带有查询参数的有效 URL[^1]。 --- #### 解析 POST 数据的方法 `parsePostData` 是另一个常见的功能,它解析来自 HTTP POST 请求的数据流并将数据存储到哈希表中以便进一步处理。 下面是一个可能的实现方式: ```java import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Hashtable; public class HttpUtils { public static Hashtable<String, String> parsePostData(int len, InputStream in) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] data = new byte[len]; int bytesRead = in.read(data); while (bytesRead != -1) { buffer.write(data, 0, bytesRead); bytesRead = in.read(data); } String postData = new String(buffer.toByteArray()); String[] pairs = postData.split("&"); Hashtable<String, String> result = new Hashtable<>(); for (String pair : pairs) { String[] keyValue = pair.split("=", 2); if (keyValue.length == 2) { result.put(keyValue[0], keyValue[1]); } } return result; } } ``` 这段代码实现了读取输入流中的字节数据,并将这些数据转换成键值对形式存入哈希表的功能[^2]。 --- #### 实际应用案例 假设我们需要向某个翻译服务发送 IP 地址查询请求,则可以利用上面提到的工具类完成如下操作: ```java import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) throws Exception { String ip = "192.168.1.1"; String url = String.format( "http://www.youdao.com/smartresult-xml/search?%s", URLEncoder.encode("type=ip&q=" + ip, "UTF-8") ); System.out.println(url); } } ``` 这里展示了一个简单的例子,其中我们将目标 IP 地址嵌入到了最终形成的 URL 当中[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值