httpclient发送get请求并获取状态码
时间: 2023-11-15 20:48:04 浏览: 152
httpclient发送post请求
在Java中,可以使用Apache HttpClient库发送HTTP请求,并获取状态码。下面是一个示例代码:
```java
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
public class HttpClientExample {
public static void main(String[] args) {
String url = "https://www.example.com";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Status Code : " + statusCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
上述代码中,我们使用HttpClientBuilder创建一个HttpClient实例。然后,我们使用HttpGet创建一个HTTP GET请求,并将其发送到指定的URL。最后,我们从响应中获取状态码,以确定请求是否成功。
阅读全文