經(jīng)過(guò)多番努力,問(wèn)題終于得到解決。感謝校長(zhǎng)的提示。 在此說(shuō)明解決方法: 同樣類似使用代理的意念,在java內(nèi)寫一個(gè)servlet來(lái)處理這個(gè)問(wèn)題。 詳細(xì)處理方式是:1.首先,同樣使用xmlhttp方式處理; 2.然后,在進(jìn)行open提交的時(shí)候,不直接提交到對(duì)應(yīng)數(shù)據(jù)源所在的URL地址。而是提交到代理程序,而通過(guò)代理程序打開需要讀取的數(shù)據(jù)源URL,同時(shí)處理讀取并返回。 3.最后,重新用xmlhttp進(jìn)行解析顯示處理即可以實(shí)現(xiàn)跨域讀取RSS源。 修改上面的js代碼: var PROXY_SERVLET_URL="../../proxyServlet?url=";//對(duì)應(yīng)配置的servlet參數(shù) 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); } } } }
|