java http get请求
时间: 2023-09-10 10:10:59 浏览: 90
Java中发送HTTP GET请求可以使用HttpURLConnection或HttpClient两种方式。
1. 使用HttpURLConnection发送GET请求:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class HttpGetExample {
public static void main(String[] args) throws IOException {
String url = "http://www.example.com/api/getData";
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 Body : " + response.toString());
}
}
```
2. 使用HttpClient发送GET请求:
```java
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;
import java.io.IOException;
public class HttpGetExample {
public static void main(String[] args) throws IOException {
String url = "http://www.example.com/api/getData";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("User-Agent", "Mozilla/5.0");
httpGet.addHeader("Accept-Language", "en-US,en;q=0.5");
httpGet.addHeader("Accept-Encoding", "gzip, deflate");
httpGet.addHeader("Connection", "keep-alive");
httpGet.addHeader("Content-Type", "application/json");
String responseBody = httpClient.execute(httpGet, response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
return EntityUtils.toString(response.getEntity());
} else {
throw new IOException("Unexpected response status: " + status);
}
});
System.out.println("Response Body : " + responseBody);
httpClient.close();
}
}
```
阅读全文