使用Java编写HTTP客户端请求示例
在Java中,我们可以使用Apache HttpClient或者java.net.URLConnection来发送HTTP请求。以下是一个使用HttpClient的简单示例:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;
public class HttpClientRequest {
public static void main(String[] args) {
// 创建HttpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 发送GET请求
HttpGet httpGet = new HttpGet("http://example.com"); // 替换为你要访问的URL
// 获取响应
CloseableHttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) { // 如果状态码是200(表示成功),
HttpEntity entity = response.getEntity(); // 获取实体内容
if (entity != null && entity.getContentLength() > 0) { // 如果实体内容非空
String jsonString = EntityUtils.toString(entity, "UTF-8")); // 将实体内容转换为字符串
JSONObject jsonObject = new JSONObject(jsonString); // 将字符串解析为JSONObject
System.out.println(jsonObject); // 打印解析后的JSON对象
}
} else { // 如果状态码不是200
System.out.println("Failed to fetch data. Status code: " + response.getStatusLine().getStatusCode());
}
// 关闭资源
response.close();
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这个示例中,我们创建了一个HttpClient实例,然后使用HttpGet发送一个GET请求到指定的URL。如果返回的状态码是200,我们就打印出响应的数据。
还没有评论,来说两句吧...