经过多番努力,问题终于得到解决。感谢校长的提示。 在此说明解决方法: 同样类似使用代理的意念,在java内写一个servlet来处理这个问题。 详细处理方式是:1.首先,同样使用xmlhttp方式处理; 2.然后,在进行open提交的时候,不直接提交到对应数据源所在的URL地址。而是提交到代理程序,而通过代理程序打开需要读取的数据源URL,同时处理读取并返回。 3.最后,重新用xmlhttp进行解析显示处理即可以实现跨域读取RSS源。 修改上面的js代码: var PROXY_SERVLET_URL="../../proxyServlet?url=";//对应配置的servlet参数 if(url.toLowerCase().indexOf("[url=http://]http://")==-1[/url]){ readRSS(url); }else{ url = PROXY_SERVLET_URL + url; readRSS(url); } java源代码如下: package action; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ProxyServletUtil extends HttpServlet { /** * */ private static final long serialVersionUID = 1L;
private int READ_BUFFER_SIZE = 1024;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String urlString = request.getParameter("url"); writeResponse(response, urlString); }
private void writeResponse(HttpServletResponse response, String urlString) throws ServletException{ try { URL url = new URL(urlString); URLConnection urlConnection = url.openConnection(); response.setContentType(urlConnection.getContentType()); InputStream ins = urlConnection.getInputStream(); OutputStream outs = response.getOutputStream(); byte[] buffer = new byte[READ_BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = ins.read(buffer, 0, READ_BUFFER_SIZE)) != -1) { outs.write(buffer, 0, bytesRead); } System.out.println(outs); outs.flush(); outs.close(); ins.close(); } catch (Exception e) { try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (IOException ioe) { throw new ServletException(ioe); } } } }
|