java httpclient教程_Java发送http请求方法之CloseableHttpClient

时间:2025-02-18 08:59:08

1.依赖

httpclient

4.5.2

2.请求步骤

使用帮助类HttpClients创建CloseableHttpClient对象.

基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例.

使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.

可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

通过执行此HttpGet或者HttpPost请求获取CloseableHttpResponse实例

从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.

释放连接。无论执行方法是否成功,都必须释放连接

3、GET方法

public void httpGet() {

CloseableHttpClient httpclient = ();

try {

// 创建httpget.

HttpGet httpget = new HttpGet("/");

("executing request " + ());

// 执行get请求.

CloseableHttpResponse response = (httpget);

try {

// 获取响应实体

HttpEntity entity = ();

// 打印响应状态

(());

if (entity != null) {

// 打印响应内容长度

("Response content length: " + ());

// 打印响应内容

("Response content: " + (entity));

}

} finally {

();

}

} catch (ClientProtocolException e) {

();

} catch (ParseException e) {

();

} catch (IOException e) {

();

} finally {

// 关闭连接,释放资源

try {

();

} catch (IOException e) {

();

}

}

}

4、POST方法

public static String httpPost(String host, int port, byte[] buf)

{

CloseableHttpClient httpClient = ();

CloseableHttpResponse httpResponse = null;

BufferedReader reader = null;

StringBuffer response = new StringBuffer();

try {

String url = "http://" + host + ":" + port;

HttpPost httpPost = new HttpPost(url);

RequestConfig requestConfig = ().setSocketTimeout(6000).setConnectTimeout(6000).build();//设置请求和传输超时时间

(requestConfig);

("User-Agent", "Mozilla/5.0");

ByteArrayEntity entity = new ByteArrayEntity(buf);

(entity);

httpResponse = (httpPost);

reader = new BufferedReader(new InputStreamReader(

().getContent()));

String inputLine;

while ((inputLine = ()) != null) {

(inputLine);

}

}catch (Exception var){

();

}finally {

if(reader != null){

();

}

if(httpResponse != null){

();

}

();

}

return ();

}