- 使用Java标准库中的
HttpURLConnection
:
代码示例:
java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetRequestUsingHttpURLConnection {
public static void main(String[] args) {
String url = "https://api.example.com/data"; // 替换成实际的API地址
try {
URL apiUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
System.out.println(response.toString());
} else {
System.out.println("GET request failed. Response code: " + responseCode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 使用OkHttp库:
安装依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
java
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class GetRequestUsingOkHttp {
public static void main(String[] args) {
String url = "https://api.example.com/data"; // 替换成实际的API地址
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.get()
.build();
try {
Response response = httpClient.newCall(request).execute();
if (response.isSuccessful()) {
String responseData = response.body().string();
System.out.println(responseData);
} else {
System.out.println("GET request failed. Response code: " + response.code());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}