方法1:利用URLConnection獲取頁面利用response轉發到自己網頁
public void index(HttpServletResponse response) throws IOException { /** * 首先要和URL下的URLConnection對話。 URLConnection可以很容易的從URL得到。比如: // Using * java.net.URL and //java.net.URLConnection */ URL url; StringBuilder sb = new StringBuilder() ; String encoding = "utf-8"; try { url = new URL("http://v.baidu.com"); URLConnection conn = url.openConnection(); if(conn.getContentEncoding()!=null) encoding = conn.getContentEncoding(); try(InputStream raw = conn.getInputStream()){//自動關閉 InputStream buffer = new BufferedInputStream(raw); Reader reader = new InputStreamReader(buffer,encoding); int c; while((c=reader.read())!=-1) { sb.append((char)c); } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.setCharacterEncoding(encoding); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(sb); out.flush(); return ; }
方法2:利用httpclient