java傳送get請求帶引數

XiaoNiuFeiTian發表於2024-06-10

在Java中,你可以使用java.net.HttpURLConnection或者org.apache.http.client.HttpClient來傳送GET請求。以下是使用java.net.HttpURLConnection傳送帶引數的GET請求的示例程式碼:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.io.IOException;
 
public class HttpGetRequest {
 
    public static String sendGetRequest(String url, Map<String, String> queryParams) throws IOException {
        StringBuilder urlBuilder = new StringBuilder(url);
        if (queryParams != null && !queryParams.isEmpty()) {
            urlBuilder.append("?");
            for (Map.Entry<String, String> entry : queryParams.entrySet()) {
                urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            urlBuilder.setLength(urlBuilder.length() - 1); // 移除最後一個"&"
        }
 
        URL obj = new URL(urlBuilder.toString());
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 
        // 設定請求方法為GET
        con.setRequestMethod("GET");
 
        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);
 
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
        String inputLine;
        StringBuilder response = new StringBuilder();
 
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
 
        return response.toString();
    }
 
    public static void main(String[] args) {
        try {
            String url = "http://example.com/api";
            Map<String, String> queryParams = Map.of("param1", "value1", "param2", "value2");
            String response = sendGetRequest(url, queryParams);
            System.out.println(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在這個例子中,sendGetRequest方法接受一個URL和一個引數Map,然後構建URL,併傳送GET請求。返回的響應會被讀取並返回。main方法展示瞭如何呼叫這個方法。

參考:百度AI

相關文章