电脑技术学习

java.net.URL如何通过proxy访问internet资源

dn001
内容: 出自:yesky finlay
对于在局域网内发布的java应用程序,由于其没有直接连接在internet上,所以不能直接用java.net.URL访问网上资源。在这种情况下,需要为java.net.URL指定代理服务器,指定方法如下所示:

import java.util.Properties;

import java.net.*;

import java.io.*;

public class TestHttpProxy {

 public static void main(String[] args) {

  String sUrl = "http://java.sun.com/index.html";

  Properties prop = System.getProperties();

  prop.put("http.proxyHost","192.168.1.111");

  prop.put("http.proxyPort","80");

  try{

   URL su = new URL(sUrl);

   System.out.println("url : " + su);

   URLConnection uc = su.openConnection();

   System.out.println("uc : " + uc);

   InputStream is = su.openStream();

   System.out.println("ic : " + is.read());

   is.close();

   System.out.println("ok");

  } catch(Exception e) {

   e.printStackTrace();

  }

 }

}

Java, java, J2SE, j2se, J2EE, j2ee, J2ME, j2me, ejb, ejb3, JBOSS, jboss, spring, hibernate, jdo, struts, webwork, ajax, AJAX, mysql, MySQL, Oracle, Weblogic, Websphere, scjp, scjd

标签: