[JAVA]GET方法帶請求體呼叫API

  • 31
  • 0

最近跟某家公司合作,對方開了一個GET方法帶請求體的API,試過Spring boot的restTemplate物件、Apache Http Client、OkHttpClient都無法於呼叫API時傳入Request Body,最後找到一篇有人使用AsyncHttpClient成功傳入的作法。 

1.Maven

<dependency>
  <groupId>org.asynchttpclient</groupId>
  <artifactId>async-http-client</artifactId>
  <version>2.12.3</version>
</dependency>

2.JAVA CODE

import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.Dsl;
import org.asynchttpclient.Request;
import org.asynchttpclient.RequestBuilder;
import org.asynchttpclient.Response;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class AsyncHttpClientExample {

    public static void main(String[] args) {
        // 創建AsyncHttpClient
        AsyncHttpClient client = Dsl.asyncHttpClient();

        // 請求URL和請求體
        String pUrl = "http://example.com/api";
        String pBody = "{\"key\":\"value\"}";

        // 創建Header的Map
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", "Bearer your_token_here");
        headers.put("Custom-Header-Name", "Custom-Header-Value");

        // 構建請求並設置標頭
        RequestBuilder requestBuilder = new RequestBuilder("GET")
                .setUrl(pUrl)
                .setBody(pBody); // 嘗試添加請求體

        // 從Map中添加標頭
        for (Map.Entry<String, String> header : headers.entrySet()) {
            requestBuilder.setHeader(header.getKey(), header.getValue());
        }

        Request request = requestBuilder.build();

        // 發送請求
        Future<Response> responseFuture = client.executeRequest(request);

        try {
            // 獲取響應
            Response response = responseFuture.get();
            System.out.println("Response: " + response.getResponseBody());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            try {
                // 關閉客戶端
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}