cross domain 訪問其他網站問題

 有人問我,我再問別人也沒看到更好的提示,還是自己google。看到這個例子(http://www.51ajax.com/bbs/viewthread.php?tid=565):

 

 

--------------------------------------------------------------------

--------------------------------------------------------------------

 

在此說明解決方法: 同樣類似使用代理的意念,在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);
    }
   }
   }
}

 

--------------------------------------------------------------------

--------------------------------------------------------------------

 

 

原來想用一個javascript寫的例子就最好了,直接給不大會編程的人也容易懂些。現在看,可以採用上面的方式,不過我覺得我還是直接用java寫個程序來實現就得了。servlet + xmlhttp 稍微有點不大好懂。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章