使用HttpClient实现请求转发功能

由于移动端要显示业务系统的数据,但是业务系统众多,如果直接和业务系统交互,会紧耦合,杂乱无章,不好管理,特编写请求转发组件,实现统一中转。

本文基于HttpClient实现了GET和POST两种方式:

GET请求:

/**
  * 根据GET方式请求获取请求内容
  * @param url
  * @return
  */
 private String getContentFromUrlByGet(String url) {
  String content = "";
  try {
   HttpClient client = new HttpClient();
   GetMethod getMethod = new GetMethod(url);
   client.executeMethod(getMethod);
   InputStream stream = getMethod.getResponseBodyAsStream(); 
   int length;
   byte[] buffer = new byte[1024 * 4];
   StringBuffer stringBuffer = new StringBuffer();
   while ((length = stream.read(buffer)) != -1) {
    stringBuffer.append(new String(buffer, 0, length, "utf-8"));
   }
   content = new String(stringBuffer);
   getMethod.releaseConnection();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return content;

 }

POST请求:

/**
  * 根据POST请求获取请求内容
  * @param url
  * @return
  */ 
 private String getContentFromUrlByPost(String url) {
  String content = "";
  try {
   HttpClient client = new HttpClient();
   PostMethod postMethod = new PostMethod(url);
   // 增加变量
   postMethod.addParameter("name", "name");
   postMethod.addParameter("pwd", "pwd");
   client.executeMethod(postMethod);
   InputStream stream = postMethod.getResponseBodyAsStream(); 
   int length;
   byte[] buffer = new byte[1024 * 4];
   StringBuffer stringBuffer = new StringBuffer();
   while ((length = stream.read(buffer)) != -1) {
    stringBuffer.append(new String(buffer, 0, length, "utf-8"));
   }
   content = new String(stringBuffer);
   postMethod.releaseConnection();
  } catch (Exception e) {
     e.printStackTrace();
  }
  return content;

 }

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值