熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java設置代理IP訪問網站

2022-06-13   來源: Java核心技術 

  源碼

  import javaioBufferedInputStream;

  import URL;

  import URLConnection;

  public class TestProxyIp {

  public static void main(String args[]){

  //SystemgetProperties()setProperty(proxySet true); //如果不設置只要代理IP和代理端口正確此項不設置也可以

  SystemgetProperties()setProperty(httpproxyHost );

  SystemgetProperties()setProperty(httpproxyPort );

  Systemoutprintln(getHtml()); //判斷代理是否設置成功

  }

  private static String getHtml(String address){

  StringBuffer html = new StringBuffer();

  String result = null;

  try{

  URL url = new URL(address);

  URLConnection conn = urlopenConnection();

  connsetRequestProperty(UserAgentMozilla/ (compatible; MSIE ; Windows NT ; GTB; NET CLR ; CIBA));

  BufferedInputStream in = new BufferedInputStream(conngetInputStream());

  try {

  String inputLine;

  byte[] buf = new byte[];

  int bytesRead = ;

  while (bytesRead >= ) {

  inputLine = new String(buf bytesRead ISO);

  htmlappend(inputLine);

  bytesRead = inread(buf);

  inputLine = null;

  }

  buf = null;

  } finally {

  inclose();

  conn = null;

  url = null;

  }

  result = new String(htmltoString()trim()getBytes(ISO) gb)toLowerCase();

  }catch(Exception e){

  eprintStackTrace();

  return null;

  }

  html = null;

  return result;

  }

  }

  結果

  

  說明:如果代理IP地址不正確將使用原有IP訪問 如果代理端口不正確將無法訪問


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26141.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.