Java11 HttpClientUtil

本文内容如有错误、不足之处,欢迎技术爱好者们一同探讨,在本文下面讨论区留言,感谢。欢迎转载,转载请注明出处(https://blog.csdn.net/feng_xiaoshi/article/details/106083539),谢谢。

下面的工具类是根据 Java11 java.net 包的 http 相关类创建。

HttpClientUtil.java

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.WebSocket;
import java.net.http.HttpRequest.Builder;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.springframework.util.CollectionUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * HttpClientUtil
 */
@Slf4j
public class HttpClientUtil {

    private static final String DEFAULT_ENCODING = "UTF-8";
    private static final int DEFAULT_READ_TIMEOUT = 50000;
    private static final int DEFAULT_CONNECT_TIMEOUT = 50000;
    private static final int DEFAULT_CONNECTION_REQUEST_TIMEOUT = 10000;
    private static final int DEFAULT_SOCKET_TIMEOUT = 50000;
    private static Map<String, String> default_get_header;

    public HttpClientUtil() {
        default_get_header.put("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36");
        default_get_header.put("Content-Type", "application/x-www-form-urlencoded");
    }

    // get请求
    public static void get(Map<String, String> params, String requestUrl, Map<String, String> headerParams) {

        HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofMillis(5000)).build();
        if (CollectionUtils.isEmpty(headerParams)) {
            headerParams = default_get_header;
        }
        Builder builder = HttpRequest.newBuilder().uri(URI.create(requestUrl))
                .timeout(Duration.ofMillis(DEFAULT_CONNECT_TIMEOUT));
        for (Map.Entry<String, String> entry : headerParams.entrySet()) {
            builder.setHeader(entry.getKey(), entry.getValue());
        }
        HttpRequest request = builder.build();
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            log.warn("http GET 请求错误", e.getMessage());
        }
    }

    // post 表单请求
    public static void post(Map<String, String> params, String requestUrl) {
        HttpClient client = HttpClient.newBuilder().build();
        // 使用 Stream 流编程将 [name1,value1],[name2,value2]...==变成==>
        // name1=value1&name2=value2&...
        var postFormParam = params.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue())
                .collect(Collectors.joining("&"));
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create(requestUrl))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .POST(HttpRequest.BodyPublishers.ofString(postFormParam)).build();

        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            log.warn("http POST 表单请求错误", e.getMessage());
        }
    }

    // post JOSN请求
    public static void post(String requestJsonParam, String requestUrl) {

        HttpRequest request = HttpRequest.newBuilder(URI.create(requestUrl))
                .timeout(Duration.ofMillis(DEFAULT_READ_TIMEOUT)).header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestJsonParam)).build();

        CompletableFuture<String> result = HttpClient.newHttpClient()
                .sendAsync(request, HttpResponse.BodyHandlers.ofString()).thenApply(HttpResponse::body);
        try {
            System.out.println(result.get());
        } catch (InterruptedException | ExecutionException e) {
            log.warn("http POST json请求错误", e.getMessage());
        }
    }

    // post 文件上传
    public static void post(File file, String fileParamKey, String requestUrl) {
        HttpClient client = HttpClient.newHttpClient();

        // Could be any string
        String boundary = "N5xJwtEHgQBVKxPs_uedAVv1Kjasjfzd5cwOR_";
        
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            HttpRequest request = HttpRequest.newBuilder().uri(URI.create(requestUrl))
                    .header("Content-Type", "multipart/form-data; boundary=" + boundary)
                    .POST(HttpRequest.BodyPublishers.ofInputStream(()->fileInputStream.nullInputStream())).build();
            HttpResponse<String>  response = client.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (FileNotFoundException e) {
            log.warn("文件找不到", file.getPath());
        }catch (IOException | InterruptedException e) {
            log.warn("http POST 文件请求错误", file.getPath());
        }

    }

    // get 文件下载
    public static void download(String filePath ,String requestUrl){
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
          .uri(URI.create(requestUrl))
          .build();
        
        CompletableFuture<Path> result = client.sendAsync(request, HttpResponse.BodyHandlers.ofFile(Paths.get(filePath)))
          .thenApply(HttpResponse::body);
        try {
			result.get();
		} catch (InterruptedException | ExecutionException e) {
			log.warn("文件下载失败", filePath);
		}
    }

    // 并发请求
    public static void concurrencyRequest(String... requestUrl){
        HttpClient client = HttpClient.newHttpClient();
        List<String> urls = List.of(requestUrl);
        List<HttpRequest> requests = urls.stream()
            .map(url -> HttpRequest.newBuilder(URI.create(url)))
            .map(reqBuilder -> reqBuilder.build()
            .collect(Collectors.toList());
        ?
        ?List<CompletableFuture<HttpResponse<String>>> futures = requests.stream()
                .map(request -> client.sendAsync(request, HttpResponse.BodyHandlers.ofString()))
                .collect(Collectors.toList());
        futures.stream().forEach(e -> e.whenComplete((resp,err) -> {
            if(err != null){
                log.warn("并发请求失败");
            }else{
                var body = resp.body();
                var statusCode = resp.statusCode();
            }
        }));
        CompletableFuture.allOf(futures.toArray(CompletableFuture<?>[]::new)).join();
    }

    // websocket 发送
    public static void sendWebSocket(String text,String webSocketUrl){
        HttpClient client = HttpClient.newHttpClient();
        WebSocket webSocket = client.newWebSocketBuilder()
            .buildAsync(URI.create(webSocketUrl), new WebSocket.Listener() {
                @Override
                public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
                    webSocket.request(1);
                    return CompletableFuture.completedFuture(data).thenAccept(System.out::println);
                }
            }).join();
        webSocket.sendText(text, false);
        
        webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "ok").join();
    }

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java常用的Httpclient工具是HttpclientUtilHttpclientUtil是一个基于Apache HttpClient组件封装的工具类,它提供了简洁的接口和方法,使得Java开发者可以轻松地进行HTTP请求的发送和接收。 HttpclientUtil的主要特点和用途包括以下几个方面: 1. 发送HTTP请求:HttpclientUtil提供了get和post两种发送HTTP请求的方法,开发者可以根据需要选择合适的方法。发送请求时,可以设置请求头、请求参数、超时时间等。 2. 接收HTTP响应:HttpclientUtil能够接收HTTP响应,并对响应进行处理。开发者可以通过获取响应头、响应体等信息,实现对响应的解析和处理。 3. 支持HTTPS:HttpclientUtil对HTTPS请求也提供了支持,可以实现HTTPS请求的发送和接收。同时,也支持自定义HTTPS证书的配置,提高了安全性。 4. 连接池管理:HttpclientUtil使用连接池来管理HTTP连接,可以有效地提高请求的性能和效率。连接池可以复用已经建立的连接,减少了连接的建立和关闭的次数。 5. 支持cookie管理:HttpclientUtil能够自动管理请求和响应中的cookie信息,简化了开发者对cookie的处理过程。 6. 异步请求:HttpclientUtil支持异步请求,可以实现并发发送多个HTTP请求,并对响应进行处理。 总的来说,HttpclientUtil是一个功能强大、使用简便的Httpclient工具类,它方便了Java开发者进行HTTP请求的发送和接收,并提供了丰富的功能和选项,以满足不同的需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值