您的位置:首页 > 理论基础 > 计算机网络

使用HttpClient实现请求转发功能

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

本文基于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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: