使用Java实现HTTP客户端的基本请求
在Java中,我们可以使用HttpURLConnection或Apache HttpClient来发送基本的HTTP请求。这里以HttpURLConnection为例:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class SimpleHttpClient {
public static void main(String[] args) {
// 创建URL对象
URL url = new URL("http://example.com");
// 发送GET请求
try (HttpURLConnection connection = (HttpURLConnection) url.openConnection()) {
// 设置连接为非KeepAlive模式
connection.setRequestProperty("Connection", "close");
// 执行GET请求
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应数据
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null)) {
content.append(inputLine);
}
in.close();
System.out.println("Response Content: " + content.toString());
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
}
这段代码创建了一个HTTP GET请求到http://example.com
。如果服务器响应,内容将被打印出来。同时,它还处理了可能的异常情况。
还没有评论,来说两句吧...