java使用get请求
时间: 2023-11-01 21:08:06 浏览: 48
在Java中使用GET请求可以使用HttpURLConnection或者HttpClient来实现。下面给出了两种方法的示例代码:
1. 使用HttpURLConnection实现GET请求:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com/api/resource");
// 创建HttpURLConnection对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
conn.setRequestMethod("GET");
// 获取响应代码
int responseCode = conn.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应内容
System.out.println("Response Content: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. 使用HttpClient库实现GET请求(需要导入HttpClient库):
```java
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientGetExample {
public static void main(String[] args) {
try {
// 创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpGet对象,设置请求URL
HttpGet httpGet = new HttpGet("http://example.com/api/resource");
// 发送GET请求
CloseableHttpResponse response = httpClient.execute(httpGet);
// 获取响应内容
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity);
// 打印响应内容
System.out.println("Response Content: " + responseContent);
// 关闭响应和HttpClient对象
response.close();
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上是两种常用的在Java中使用GET请求的方法,你可以根据自己的需求选择其中一种来实现。