java发送get请求
时间: 2023-08-29 12:11:18 浏览: 37
Java 可以使用 HttpURLConnection 或者 HttpClient 来发送 GET 请求。
使用 HttpURLConnection 发送 GET 请求的示例代码:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpGetRequest {
public static void main(String[] args) throws Exception {
String url = "https://www.example.com/api/data";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
```
使用 HttpClient 发送 GET 请求的示例代码:
```
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpGetRequest {
public static void main(String[] args) throws Exception {
String url = "https://www.example.com/api/data";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code : " + statusCode);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
}
}
```
以上代码中,url 是要请求的地址,使用 HttpURLConnection 或者 HttpClient 发送 GET 请求,然后获取响应体的内容进行处理。