1. 首先在工程中加入commons-httpclient-3.0.jar
2. 应用方法实例:
public ModelAndView dispatchPage(HttpServletRequest request,
HttpServletResponse response) throws IOException, ClassNotFoundException{
// 创建 HttpClient 的实例
HttpClient httpClient = new HttpClient();
//获得跳转地址
String url = "http://192.168.23.13/XXXX/Y.do";
PostMethod postMethod = new PostMethod(url);
// 获取参数值并传入
postMethod.addParameter("KEY", "VALUE");
postMethod.addParameter("KEY", "VALUE");
// 执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
//输出回应
InputStream is = postMethod.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,
"utf-8"));
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
}
//查看缓存
Cookie[] cookies = httpClient.getState().getCookies();
System.out.println("cookies length = " + cookies.length + " state="
+ statusCode);
for (int i = 0; i < cookies.length && cookies.length!=0; i++) {
System.out.println("cookie - " + i + ":");
System.out.println(cookies.toString());
System.out.println(cookies[i].getDomain());
System.out.println(cookies[i].getName());
System.out.println(cookies[i].getPath());
System.out.println(cookies[i].getValue());
System.out.println("---------------------");
}
int a = HttpStatus.SC_OK;
Map m = new HashMap();
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
// 301或者302
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
Header header = postMethod.getResponseHeader("location");
String location = null;
if (header != null) {
location = header.getValue();
System.out.println("aaaaaaaa" + location);
if((location == null) || location.equals("")){
location = "/";
}
GetMethod redirect = new GetMethod(location);
httpClient.executeMethod(redirect);
redirect.releaseConnection();
//存放最终跳转的链接
m.put("dispatchUrl", location);
}else{
//System.out.println("bbbbbbbbbbbbb");
}
postMethod.releaseConnection();
}
return new ModelAndView("dispatchPage",m);
}
3. 页面dispatchPage跳转写法
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/taglibs.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>页面跳转中</title>
<script language="javascript" type="text/javascript">
window.location.href="${dispatchUrl}";
</script>
</head>
<body>
页面正在跳转中。。。请稍候。。。
</body>
</html>