httpclient5 发送get请求
时间: 2023-08-31 11:05:09 浏览: 150
HttpClient GET请求
以下是使用httpclient5发送get请求的示例代码:
```java
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.protocol.BasicHttpContext;
import org.apache.hc.core5.http.protocol.HttpContext;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient httpClient = HttpClient.newBuilder().build();
HttpContext context = new BasicHttpContext();
HttpGet httpGet = new HttpGet("https://www.example.com");
HttpResponse httpResponse = httpClient.execute(httpGet, context);
String responseString = EntityUtils.toString(httpResponse.getEntity());
System.out.println(responseString);
}
}
```
在这个示例中,我们创建了一个HttpClient实例并使用它来执行一个HttpGet请求。我们还创建了一个HttpContext实例,以便我们可以在请求和响应之间共享状态。我们使用EntityUtils类将响应实体转换为字符串,并在控制台上打印它。
阅读全文