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();
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章