HttpClient

1.简介

HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,

2.主要功能

  • 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
  • 支持自动转向
  • 支持 HTTPS 协议
  • 支持代理服务器等

3.执行get请求

不带参数

// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http GET请求
HttpGet httpGet = new HttpGet("http://www.baidu.com/");
//创建响应
CloseableHttpResponse response = null;
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
      //读取响应内容
      String content =EntityUtils.toString(response.getEntity(), "UTF-8");
      System.out.println("内容长度:" + content.length());
      //将内容写到文件中      
     //FileUtils.writeStringToFile(new File("C:\\baidu.html"), content);
 }

带参数

// 定义请求的参数
/*
多个参数
URIBuilder builder = new URIBuilder(url); /String url.
builder.addParameter(key,value));
URI uri = builder.build();
*/
URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);

4.执行post请求

不带参数

  // 创建Httpclient对象
  CloseableHttpClient httpclient = HttpClients.createDefault();
  // 创建http POST请求
  HttpPost httpPost = new HttpPost("http://www.oschina.net/");
  CloseableHttpResponse response = null;
  // 执行请求
  response = httpclient.execute(httpPost);
  // 判断返回状态是否为200
 if(response.getStatusLine().getStatusCode() == 200) {
       String content = EntityUtils.toString(response.getEntity(), "UTF-8");
       System.out.println(content);
  }

带参数

// 设置2个post参数,一个是scope、一个是q
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
parameters.add(new BasicNameValuePair(key, value));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 将请求实体设置到httpPost对象中,模拟表单
httpPost.setEntity(formEntity);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值