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