Java sample codes that access outer internet through proxy which require username and password
Use inner instead of extends is the most different
There are also some articles on the Internet, but most of the proxies that involve authorization verification have problems,
The main problem is the use of Authenticator. setDefault and base64 encoding.
Code is a document with no ambiguity. The implementation principle is not explained anymore. See the code to understand it.
If it is reproduced, please indicate the code source.
Chimae@cnjsp.org
Package org.chimae.net;
Import java. io. BufferedReader;
Import java. io. IOException;
Import java. io. InputStream;
Import java. io. InputStreamReader;
Import java.net. Authenticator;
Import java.net. HttpURLConnection;
Import java.net. PasswordAuthentication;
Import java.net. URL;
/**
* @ Author chimae@cnjsp.org
*/
Public class ProxyConnTest {
Public static void initProxy (String host, int port, final String username,
Final String password ){
Authenticator. setDefault (new Authenticator (){
Protected PasswordAuthentication getPasswordAuthentication (){
Return new PasswordAuthentication (username,
New String (password). toCharArray ());
}
});
System. setProperty ("http. proxyType", "4 ");
System. setProperty ("http. proxyPort", Integer. toString (port ));
System. setProperty ("http. proxyHost", host );
System. setProperty ("http. proxySet", "true ");
}
Public static void main (String [] args) throws IOException {
String url = "http://java.sun.com /";
String proxy = "yourProxy ";
Int port = 8080;
String username = "username ";
String password = "password ";
String curLine = "";
String content = "";
URL server = new URL (url );
InitProxy (proxy, port, username, password );
HttpURLConnection connection = (HttpURLConnection) server. openConnection ();
Connection. connect ();
InputStream is = connection. getInputStream ();
BufferedReader reader = new BufferedReader (new InputStreamReader (is ));
While (curLine = reader. readLine ())! = Null ){
Content + = curLine;
}
System. out. println ("content =" + content );
Is. close ();
}
}