Java中HTTP请求怎么发送
在Java中发送HTTP请求,你可以使用多种方法。以下是一些常用的方法:
- 使用
java.net.HttpURLConnection(适用于Java 1.1及以上版本):
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetRequest {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
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());
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 使用
java.net.URL和java.io.InputStream(适用于简单的GET请求):
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
public class SimpleHttpGetRequest {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com");
InputStream inputStream = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 使用第三方库,如Apache HttpClient(适用于更复杂的HTTP请求和更好的错误处理):
首先,你需要将Apache HttpClient库添加到项目的依赖中。如果你使用Maven,可以在
pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.apache.httpcomponentsgroupId>
<artifactId>httpclientartifactId>
<version>4.5.13version>
dependency>
然后,你可以使用以下代码发送GET请求:
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ApacheHttpClientExample {
public static void main(String[] args) {
try {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
String responseBody = EntityUtils.toString(httpResponse.getEntity());
System.out.println(responseBody);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这些方法中的每一个都可以用于发送HTTP请求。你可以根据你的需求和项目环境选择合适的方法。