httpclientAPI调用
时间: 2023-05-25 16:04:53 浏览: 177
HttpClient是Java的一个HTTP通讯库,可以用于发送HTTP请求和接收HTTP响应。
在使用HttpClient之前,需要先下载相关的jar包,比如httpclient、httpcore等,然后在代码中引入相关的类库。
以下是使用HttpClient发送一个HTTP GET请求的示例代码:
```
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientDemo {
public static void main(String[] args) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://www.baidu.com/");
System.out.println("Executing request " + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
EntityUtils.consume(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
该代码创建了一个CloseableHttpClient实例,然后构造一个HttpGet请求。使用httpclient.execute()方法发送该请求,并接收响应。最后使用EntityUtils.toString()方法将响应内容转换为字符串输出。最后,关闭HttpClient实例。
阅读全文