在Java中設置GET請求的參數可以通過構建URL,并在URL中添加參數。下面是一個簡單的示例代碼:
import java.net.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
String urlString = "http://example.com/api";
String param1 = "key1=value1";
String param2 = "key2=value2";
URL url = new URL(urlString + "?" + param1 + "&" + param2);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上面的示例中,我們首先構建了一個URL對象,將參數拼接在URL后面。然后使用HttpURLConnection打開連接,并設置請求方法為GET。最后讀取響應內容并輸出。