Java HTTP客户端:实现GET和POST请求案例
在Java中,我们可以使用HttpURLConnection或者Apache HttpClient来实现HTTP客户端的GET和POST请求。这里我将以HttpURLConnection为例,给出具体的案例。
创建连接:
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
设置请求方法:
connection.setRequestMethod("GET"); // GET请求
// connection.setRequestMethod("POST"); // POST请求,需要填充请求体
获取响应内容(如果为GET):
InputStream responseStream = connection.getInputStream();
StringBuilder contentBuilder = new StringBuilder();
byte[] buffer = new byte[1024];
while (responseStream != null) {
int count = responseStream.read(buffer);
if (count > 0) {
contentBuilder.append(new String(buffer, 0, count))));
}
}
String responseBody = contentBuilder.toString();
以上就是使用Java HTTP客户端实现GET和POST请求的一个基本案例。根据实际需求,你可能需要处理更多的细节,例如设置超时、添加头信息等。
还没有评论,来说两句吧...