سؤال

أرغب في إحضار صفحة SSL في جافا. المشكلة هي أنه لا بد لي من المصادقة ضد وكيل HTTP.

لذلك أريد طريقة بسيطة لجلب هذه الصفحة. حاولت Apache Armons Applient، لكنها أكثر من اللازم لمشكلتي.

حاولت هذه القطعة من التعليمات البرمجية، لكنها لا تحتوي على إجراء مصادقة:

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();
  }

نصائح أخرى

تحتاج إلى تعيين 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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top