HttpClient4 发送http请求

        最近项目中需要调用第三方平台的rest API,需要用到httpClient来发送http请求。简单封装了一个工具类。

        下来具体说一下httpClient的使用首先得需要依赖 httpcore-4.4.3.jar和httpclient-4.5.1.jar,如果需要发送异步请求还需要httpasyncclient-4.1.1.jar和httpcore-nio-4.4.4.jar获取方法网上有很多 官方现在地址http://hc.apache.org/downloads.cgi,我使用的httpclient-4.5.1.jar。
  1.使用httpclient 发送Get和Post请求

     //get 请求
      CloseableHttpClient httpclient = HttpClients.createDefault();
         try {
        HttpGet httpGet = new HttpGet("http://www.baidu.com");
       System.out.println("Executing get request " + httpGet.getURI());
       CloseableHttpResponse response = httpclient.execute(httpGet);
           try {
              System.out.println(response.getStatusLine()); //返回请求的响应码
                httpGet.abort();
             } finally {
                 response.close();
             }
           } finally {
                httpclient.close();
          }
    //Post 请求            
     CloseableHttpClient httpclient = HttpClients.createDefault();
       try {
           HttpPost httpPost = new HttpPost("http://www.baidu.com");
       List<NameValuePair> pairList = new ArrayList<NameValuePair>();
        pairList.add(new BasicNameValuePair("参数名","参数值"));
       System.out.println("Executing get request " + httpPost.getURI());
       CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
           System.out.println(response.getStatusLine()); //返回请求的响应码
              httpPost.abort();
           } finally {
              response.close();
            }
        } finally {
                httpclient.close();
      }

 

转载于:https://my.oschina.net/CPFspace/blog/758017

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值