日期:2014-05-17 浏览次数:20865 次
// 这是模拟post请求
public static Result sendPost(String url, Map<String, String> headers, Map<String, String> params, String encoding,boolean isProxy) throws ClientProtocolException, IOException {
// 实例化一个post请求
HttpPost post = new HttpPost(url);
DefaultHttpClient client = new DefaultHttpClient();
if (isProxy) {//是否开启代理
HttpHost proxy = new HttpHost("221.181.192.30", 85);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
// 设置需要提交的参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
if (params != null) {
for (String temp : params.keySet()) {
list.add(new BasicNameValuePair(temp, params.get(temp)));
}
}
post.setEntity(new UrlEncodedFormEntity(list, encoding));
// 设置头部
if (null != headers)
post.setHeaders(assemblyHeader(headers));
// 实行请求并返回
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
HttpEntity entityRsp = response.getEntity();
StringBuffer result1 = new StringBuffer();
BufferedReader rd = new BufferedReader(new InputStreamReader(entityRsp.getContent(), encoding));
String tempLine = rd.readLine();
// 封装返回的参数
Result result = new Result();
while (tempLine != null) {
// 返回获取请求地址
// if (tempLine.contains("encodeURI('")) {
// System.out.println("encode:" +
// tempLine.substring(tempLine.indexOf("encodeURI('") + 11,
// tempLine.indexOf("');")));
// }
result1.append(tempLine);
tempLine = rd.readLine();
}
// 设置返回状态代码
result.setStatusCode(response.getStatusLine().getStatusCode());
// 设置返回的头部信息
result.setHeaders(response.getAllHeaders());
// 设置返回的cookie信心
result.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
// 设置返回到信息
result.setHttpEntity(entity);
return result;
}