通过Java实现HTTP请求与响应示例
在Java中,我们可以使用Apache HttpClient库来发送HTTP请求和接收响应。以下是一个简单的示例:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
public class HttpExample {
public static void main(String[] args) {
// 创建一个HttpGet请求对象
HttpGet httpget = new HttpGet("http://example.com");
try (CloseableHttpResponse response =HttpClientBuilder.create().build().execute(httpget)) {
// 获取响应状态码
int status_code = response.getStatusLine().getStatusCode();
// 如果是2xx的成功状态,就获取并打印实体数据
if (status_code >= 200 && status_code < 300) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String content = EntityUtils.toString(entity);
System.out.println("Response Content: " + content);
}
} else {
System.out.println("Error occurred. Status code: " + status_code);
}
// 关闭响应
response.close();
} catch (Exception e) {
e.printStackTrace();
}
}
在这个示例中,我们发送了一个GET请求到http://example.com
。然后打印出服务器的响应内容。
请确保已经添加了Apache HttpClient库到你的项目中。
还没有评论,来说两句吧...