我想用Java获取SSL页面。问题是,我必须对http代理进行身份验证。
所以我想要一个简单的方法来获取这个页面。 我尝试了Apache Commons httpclient,但这对我的问题来说太多了。
我尝试了这段代码,但它不包含身份验证操作:
import java.io.*;
import java.net.*;
public class ProxyTest {
public static void main(String[] args) throws ClientProtocolException, IOException {
URL url = new URL("https://ssl.site");
Socket s = new Socket("proxy.address", 8080);
Proxy proxy = new Proxy(Proxy.Type.HTTP, s.getLocalSocketAddress());
URLConnection connection = url.openConnection(proxy);
InputStream inputStream = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String tmpLine = "";
while ((tmpLine = br.readLine()) != null) {
System.out.println(tmpLine);
}
}
}
任何人都可以提供一些如何以简单的方式实现它的信息吗?
提前致谢
答案 0 :(得分:6)
在打开连接之前,您需要设置java.net.Authenticator:
...
public static void main(String[] args) throws Exception {
// Set the username and password in a manner which doesn't leave it visible.
final String username = Console.readLine("[%s]", "Proxy Username");
final char[] password = Console.readPassword("[%s"], "Proxy Password:");
// Use a anonymous class for our authenticator for brevity
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
URL url = new URL("https://ssl.site");
...
}
要在完成后删除身份验证器,请调用以下代码:
Authenticator.setDefault(null);
Java SE 6中的身份验证器支持HTTP Basic
,HTTP Digest
和 NTLM
。有关详细信息,请参阅sun.com上的Http Authentication文档
答案 1 :(得分:4)
org.apache.commons.httpclient.HttpClient是你的朋友,
来自http://hc.apache.org/httpclient-3.x/sslguide.html
的示例代码 HttpClient httpclient = new HttpClient();
httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);
httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
GetMethod httpget = new GetMethod("https://www.verisign.com/");
try {
httpclient.executeMethod(httpget);
System.out.println(httpget.getStatusLine());
} finally {
httpget.releaseConnection();
}
答案 2 :(得分:0)
使用apache commons-http-client 4: 你会发现很多例子@ http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/examples/org/apache/http/examples/client/