java 中如何 发送http请求
时间: 2023-10-12 07:06:04 浏览: 35
在 Java 中可以使用 HttpURLConnection 或 HttpClient 类来发送 HTTP 请求。
使用 HttpURLConnection 发送 HTTP 请求的示例:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpUrlConnectionExample {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
```
使用 HttpClient 发送 HTTP 请求的示例:
```java
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 HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://example.com");
String response = httpClient.execute(request, response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
return EntityUtils.toString(response.getEntity());
} else {
throw new Exception("Unexpected response status: " + status);
}
});
System.out.println(response);
}
}
```
需要注意的是,以上示例中的 URL 和请求方法需要根据实际情况进行修改。