1、后台请求获取网页内容
public static String getDataFromURL(String strURL, Map<String, Object> param) throws Exception { URL url = new URL(strURL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); final StringBuilder sb; if (param != null) { sb = new StringBuilder(param.size() << 4);// 4次方 final Set<String> keys = param.keySet(); for (final String key : keys) { final Object value = param.get(key); sb.append(key); // 不能包含特殊字符 sb.append('='); sb.append(value); sb.append('&'); } // 将最后的 '&' 去掉 sb.deleteCharAt(sb.length() - 1); }else{ sb = new StringBuilder(100 << 4); } // writer.write("email=fd3589@163.com&password=123"); writer.write(sb.toString()); writer.flush(); writer.close(); InputStreamReader reder = new InputStreamReader(conn.getInputStream(), "utf-8"); BufferedReader breader = new BufferedReader(reder); BufferedWriter w = new BufferedWriter(new FileWriter("d:/1.txt"));//获取内容输出到指定文件 String content = null; String result = null; while ((content = breader.readLine()) != null) { result += content; } w.write(result); w.flush(); w.close(); return result; }
2、后台Servlet的代码
@RequestMapping("URLtoHtml") public void URLtoHtml(HttpServletRequest request,HttpServletResponse response) throws IOException{ String strURL= request.getParameter("url"); String html= etDataFromURL(strURL, null);;//获取的html代码 response.setContentType("text/html;charset=utf-8"); PrintWriter out=response.getWriter(); out.println(html); }
3、iframe中通过后台接口请求页面
利用同域名下的后台api来请求要显示的网页,本文主要是要操作iframe中的文字内容,逻辑很简单,解决跨域问题,可以使用此方法。复杂可以考虑其它方法解决iframe中跨域问题。
<iframe src="URLtoHtml?url=https://www.cnblogs.com/shijiaqi1066/p/3753224.html" width="500" height="300" id="iframe"></iframe>