HttpUtils远程调用工具类


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;


public class HttpUtils {
   protected static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
   
   public static String post(String url, String jsonContent){
      PostMethod postMethod = null;
      try {
          HttpClient client = new HttpClient();
          postMethod = new PostMethod(url);
          postMethod.setRequestHeader("Content-Type", "application/json");
          postMethod.setRequestHeader("Authorization", "Basic YWRtaW46");
          RequestEntity se = new StringRequestEntity(jsonContent, "application/json", "UTF-8");
          postMethod.setRequestEntity(se);
          client.executeMethod(postMethod);
          String respBody = postMethod.getResponseBodyAsString();
          logger.info("HttpUtils post responseBody:" + respBody);
          return respBody;
       }catch (Exception e) {
          logger.error("HttpUtils post method error:"+e);
       } finally {
          if (postMethod != null) {
            postMethod.releaseConnection();
          }
       }
      return null;
   }
   
   public static String post(String url, String jsonContent,Map<String, String> headers){
      
      PostMethod postMethod = null;
      try {
         HttpClient client = new HttpClient();
         postMethod = new PostMethod(url);
         postMethod.setRequestHeader("Content-Type", "application/json");
         if (null!=headers && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
               postMethod.setRequestHeader(entry.getKey(), entry.getValue());
            }
         }
         RequestEntity se = new StringRequestEntity(jsonContent, "application/json", "UTF-8");
         postMethod.setRequestEntity(se);
         client.executeMethod(postMethod);
         String respBody = postMethod.getResponseBodyAsString();
         logger.info("HttpUtils post responseBody:" + respBody);
         return respBody;
      }catch (Exception e) {
         logger.error("HttpUtils post method error:"+e);
      } finally {
         if (postMethod != null) {
            postMethod.releaseConnection();
         }
      }
      return null;
   }
   
   public static String post(String url){
      PostMethod postMethod = null;
      try {
         HttpClient client = new HttpClient();
         postMethod = new PostMethod(url);
         postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         client.executeMethod(postMethod);
         String respBody = postMethod.getResponseBodyAsString();
         logger.info("HttpUtils post responseBody:" + respBody);
         return respBody;
      }catch (Exception e) {
         logger.error("HttpUtils post method error:"+e);
      } finally {
         if (postMethod != null) {
            postMethod.releaseConnection();
         }
      }
      return null;
   }
   
   public static String postJson(String url, String jsonContent){
      PostMethod postMethod = null;
      try {
         HttpClient client = new HttpClient();
         postMethod = new PostMethod(url);
         postMethod.setRequestHeader("Content-Type", "application/json");
         RequestEntity se = new StringRequestEntity(jsonContent, "application/json", "UTF-8");
         postMethod.setRequestEntity(se);
         client.executeMethod(postMethod);
         String respBody = postMethod.getResponseBodyAsString();
         logger.info("HttpUtils postJson responseBody:" + respBody);
         return respBody;
      }catch (Exception e) {
         logger.error("HttpUtils postJson method error:"+e);
      } finally {
         if (postMethod != null) {
            postMethod.releaseConnection();
         }
      }
      return null;
   }
   
   public static String postForm(String url, NameValuePair[] nameValuePairs){
      PostMethod postMethod = null;
      try {
         HttpClient client = new HttpClient();
         postMethod = new PostMethod(url);
         postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
         postMethod.setRequestBody(nameValuePairs);
         client.executeMethod(postMethod);
         String respBody = postMethod.getResponseBodyAsString();
         logger.info("HttpUtils postForm responseBody:" + respBody);
         return respBody;
      }catch (Exception e) {
         logger.error("HttpUtils postForm method error:"+e);
      } finally {
         if (postMethod != null) {
            postMethod.releaseConnection();
         }
      }
      return null;
   }
   
   /**
    * httpclient get请求
    *
    * @throws Exception
    */
   public static String get(String url) {

      //创建一个httpclient对象
      CloseableHttpClient client = HttpClients.createDefault();

      //创建URIBuilder
      URIBuilder uri = null;
      CloseableHttpResponse response = null;
      try {
         uri = new URIBuilder(url);
         //创建httpGet对象
         HttpGet hg = new HttpGet(uri.build());

         //设置请求的报文头部的编码
         hg.setHeader(
               new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));

         //设置期望服务端返回的编码
         hg.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
         response = client.execute(hg);
         //获取响应码
         int statusCode = response.getStatusLine().getStatusCode();

         if (statusCode == 200) {

            //获取返回实例entity
            HttpEntity entity = response.getEntity();

            //通过EntityUtils的一个工具方法获取返回内容
            String resStr = EntityUtils.toString(entity, "utf-8");

            //输出
            logger.info("请求成功,请求返回内容为: " + resStr);
            return resStr;
         } else {
            //输出
            logger.info("请求失败,错误码为: " + statusCode);
            return null;
         }
      } catch (URISyntaxException e) {
         e.printStackTrace();
      } catch (ClientProtocolException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();

      }finally {
         //关闭response和client
         try {
            response.close();
            client.close();
         } catch (IOException e) {
            e.printStackTrace();
         }

      }
      return null;
   }






   public static String get(String url, String data) {
      HttpMethod method = null;
      try {
         HttpClient client = new HttpClient();
         //链接超时时间
         client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);
         //读取超时时间
         client.getHttpConnectionManager().getParams().setSoTimeout(2000);
         if (StringUtils.isNotBlank(data)) {
            url=url.concat(data);
         }
         method = new GetMethod(url);
         method.addRequestHeader("Content-Type", "text/html;charset=UTF-8");// 乱码问题
         client.executeMethod(method);
         String respBody = method.getResponseBodyAsString();
         logger.info("HttpUtils get responseBody:" + respBody);
         return respBody;
      } catch (Exception e) {
         logger.error("HttpUtils get method error:"+e);
      } finally {
         if (null != method) {
            method.releaseConnection();// 释放连接
         }
      }
      return null;
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值