jsp实现 AJAX 跨域代理2008-04-17 17:39
http://hi.baidu.com/afeiecho/blog/item/6afe39ec878946382697918f.html
proxy.jsp:
<%@ page import="java.net.*,java.util.*,java.lang.*,java.io.*"%><%@ page contentType="text/xml;charset=gb2312"%><%
String url = null;
StringBuffer params = new StringBuffer();
Enumeration enu = request.getParameterNames();
int total = 0;
while (enu.hasMoreElements()) {
String paramName=(String)enu.nextElement();
if(paramName.equals("url")){
url=request.getParameter(paramName);
}else{
if(total==0){
params.append(paramName).append("=").append(URLEncoder.encode(request.getParameter(paramName), "UTF-8"));
} else {
params.append("&").append(paramName).append("=").append(URLEncoder.encode(request.getParameter(paramName), "UTF-8"));
}
++total;
}
}
url = url + "?" + params.toString();
//out.println(url);
if(url != null){
// 使用GET方式向目的服务器发送请求
URL connect = new URL(url.toString());
URLConnection connection = connect.openConnection();
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = reader.readLine()) != null){
out.println(line);
}
reader.close();
}
%>
AJAX中不能直接访问http://www.otherpersondomain.com/a.jsp?param1=¶m2=
所以通过访问proxy.jsp代理访问:
proxy.jsp?url=http://www.otherpersondomain.com/a.jsp¶m1=¶m2=