proxytest.java

来自「数字图书馆的互操作接口」· Java 代码 · 共 74 行

JAVA
74
字号
package dli2fe.test;

import java.util.Properties;
import java.util.Date;
import java.net.URL;
import java.net.URLEncoder;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import org.w3c.tools.codec.*;
import java.io.*;

// This is a simple example that shows how to get HTTP connections to work
// with a proxy server. If all goes well, we should be able to post some
// data to a public cgi script and get back the resulting HTML.  If anyone
// knows some "gotchas" when combining Java and proxies, I'd love to hear
// about them.  Send your thoughts to kurr@ctron.com.

public class ProxyTest
{
    public static void main( String argv[] )
    {
        try
        {

            // Enable the properties used for proxy support
            System.getProperties().put( "proxySet", "true" );
            System.getProperties().put( "proxyHost", "202.120.224.4" );
            System.getProperties().put( "proxyPort", "8080" );

            // URL to a public cgi script
            URL url = new URL("http://www.fudan.edu.cn/");
            URLConnection connection = url.openConnection();

            // enter the username and password for the proxy
            String password = "xh_xh:xh_xh";

            // base64 encode the password.  You can write your own,
            // use a public domain library like
            // http://www.innovation.ch/java/HTTPClient/ or use
            // the sunw.server.admin.toolkit.security.BASE64Encoder
            // class from JavaSoft Java Web Server.
            Base64Encoder b = new Base64Encoder(password);
            String encoded = b.processString();

            // Set up the connection so it knows you are sending
            // proxy user information
            connection.setRequestProperty( "Proxy-Authorization", "Basic " + encoded );

            // Set up the connection so you can do read and writes
            connection.setDoInput( true );
            connection.setDoOutput( false );

            // open up the output stream of the connection
            //BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
            //out.write("GET test/detail.htm", 0, "GET test/detail.htm".length());
            //out.close();

            // get ready to read the response from the cgi script
            BufferedReader din = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = din.readLine()) != null) {
              System.out.println(line);
            }
        }
        catch( Exception e )
        {
            System.out.println( "Something bad just happened." );
            System.out.println( e );
            e.printStackTrace();
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?