httpclient5的execute过时了怎么办
时间: 2024-06-09 08:09:54 浏览: 7
HttpClient5的`execute`方法已经被标记为过时,建议使用`send`方法代替。`send`方法是`execute`方法的替代方法,提供了更好的性能和可扩展性。
以下是使用`send`方法发送GET请求的示例代码:
```java
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.sync.CloseableHttpClient;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;
public class HttpClientExample {
public static void main(final String[] args) throws Exception {
try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
final HttpGet httpget = new HttpGet("http://www.example.com/");
try (final ClassicHttpResponse response = httpclient.execute(httpget)) {
final String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
}
}
}
}
```
注意,`send`方法返回一个`HttpResponse`对象,需要手动关闭资源。使用try-with-resources语句可以自动关闭资源。
希望能帮到你!