Java代码发送HTTP请求可以使用java.net.HttpURLConnection
类或者第三方库如Apache HttpClient、OkHttp等。这里我将给出一个使用HttpURLConnection
的示例代码。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequestExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("响应码: " + responseCode);
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
// 关闭连接和输入流
in.close();
connection.disconnect();
// 输出响应内容
System.out.println("响应内容: " + content.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
这段代码首先创建一个URL
对象,然后使用openConnection()
方法打开一个到该URL的连接。接着设置请求方法为GET
,并获取响应码。最后,通过InputStreamReader
和BufferedReader
读取响应内容,并将其输出。