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

1.依赖

org.apache.httpcomponents

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 = HttpClients.createDefault();

try {

// 创建httpget.

HttpGet httpget = new HttpGet("http://www.baidu.com/");

System.out.println("executing request " + httpget.getURI());

// 执行get请求.

CloseableHttpResponse response = httpclient.execute(httpget);

try {

// 获取响应实体

HttpEntity entity = response.getEntity();

// 打印响应状态

System.out.println(response.getStatusLine());

if (entity != null) {

// 打印响应内容长度

System.out.println("Response content length: " + entity.getContentLength());

// 打印响应内容

System.out.println("Response content: " + EntityUtils.toString(entity));

}

} finally {

response.close();

}

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (ParseException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

// 关闭连接,释放资源

try {

httpclient.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

4、POST方法

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

{

CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse httpResponse = null;

BufferedReader reader = null;

StringBuffer response = new StringBuffer();

try {

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

HttpPost httpPost = new HttpPost(url);

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

httpPost.setConfig(requestConfig);

httpPost.addHeader("User-Agent", "Mozilla/5.0");

ByteArrayEntity entity = new ByteArrayEntity(buf);

httpPost.setEntity(entity);

httpResponse = httpClient.execute(httpPost);

reader = new BufferedReader(new InputStreamReader(

httpResponse.getEntity().getContent()));

String inputLine;

while ((inputLine = reader.readLine()) != null) {

response.append(inputLine);

}

}catch (Exception var){

var.printStackTrace();

}finally {

if(reader != null){

reader.close();

}

if(httpResponse != null){

httpResponse.close();

}

httpClient.close();

}

return response.toString();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值