iframe拒绝访问 java 读取网页内容

昨天,在应用开发中,遇到了一个iframe跨域拒绝访问的问题,在网上找了半天,最后,决定使用java重定向读取网页内容显示的办法解决,可是在java读取网页内容的时候,有碰到了乱码问题,网上也有好多的解决办法,可是都不适用,琢磨到今天,终于解决了,先贴出来,与大家分享一下。

关键语句在于:new InputStreamReader(conn.getInputStream(),
                 conn.getContentEncoding()!=null?conn.getContentEncoding():"UTF-8"))。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
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 GetHtmlContentByURL extends HttpServlet {

private static final long serialVersionUID = 1L;

public GetHtmlContentByURL() {
   super();
}

public void destroy() {
   super.destroy();
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
   String htmlUrl = request.getParameter("url");
   response.setCharacterEncoding("UTF-8");
   URL url = null;
   URLConnection conn = null;
   PrintWriter out = null;
     try { 
         out = response.getWriter();
         url = new URL(htmlUrl);
         conn = url.openConnection();
         //将网页文件默认设置为UTF-8字符集,
           BufferedReader reader = new BufferedReader(
               new InputStreamReader(conn.getInputStream(),
                 conn.getContentEncoding()!=null?conn.getContentEncoding():"UTF-8"));
            String line = null;
            while ((line=reader.readLine()) != null){
                out.println(line);
            }

        out.flush();
        reader.close();
     } catch (Exception ex) {   
         ex.printStackTrace();
     } finally { 
     if(out!=null){
        try{
         out.close();
        }catch(Exception e){
         e.printStackTrace();
        }
     }
     } 
}

public void doPost(HttpServletRequest request, 
                    HttpServletResponse response) 
                        throws ServletException, IOException {
   this.doGet(request, response);
}

public void init() throws ServletException {}
}

你可能感兴趣的:(java,.net,servlet)