Java의 프록시를 통해 SSL 페이지를 가져 오는 가장 쉬운 방법
-
05-09-2019 - |
문제
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);
}
}
}
누구든지 쉽게 구현하는 방법을 제공 할 수 있습니까?
미리 감사드립니다
해결책
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();
}
다른 팁
당신은 a를 설정해야합니다 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
. 자세한 내용은 HTTP 인증 sun.com의 문서
Apache Commons-HTTP-Client 4 : 많은 예제를 찾을 수 있습니다 @ http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/examples/org/apache/http/examples/client/
제휴하지 않습니다 StackOverflow