码迷,mamicode.com
首页 > 其他好文 > 详细

使用HttpClient实现请求转发功能

时间:2014-09-12 15:11:23      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:get   post   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;

 }

使用HttpClient实现请求转发功能

标签:get   post   httpclient   请求转发   

原文地址:http://blog.csdn.net/cwb1128/article/details/39228963

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!