使用 Java 中的基本身份验证连接到 URL - java.net.ConnectException:连接被拒绝:连接

connect to a URL using Basic authentication in Java - java.net.ConnectException: Connection refused: connect

我正在尝试连接到需要基本身份验证的网站,但我收到 java.net.ConnectException:连接被拒绝:连接,我无法获取内容,基本身份验证依赖于 Base64 编码 'Authorization' header 其值由单词 'Basic' 后跟 space 和 Base64 编码的 name:password 组成。当然,使用浏览器我得到了我想要的 json 文件

    public static void main(String[] args) {

            try {

System.setProperty("http.proxyHost", PROXY_HOST);
            System.setProperty("http.proxyPort", PROXY_PORT);
            setAuthenticator();

                String webPage = "https://foo.com/developers/apps.json";


                String name = "myUserName";
                String password = "myPassword";

                String authString = name + ":" + password;
                System.out.println("auth string: " + authString);
                byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
                String authStringEnc = new String(authEncBytes);
                System.out.println("Base64 encoded auth string: " + authStringEnc);

                URL url = new URL(webPage);
                URLConnection urlConnection = url.openConnection();

                String encoded = new String (base64Encode(new String("j0a3t:d3jk6ft")));
                urlConnection.setRequestProperty("Proxy-Authorization", "Basic " + encoded);

                urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
                InputStream is = urlConnection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);

                int numCharsRead;
                char[] charArray = new char[1024];
                StringBuffer sb = new StringBuffer();
                while ((numCharsRead = isr.read(charArray)) > 0) {
                    sb.append(charArray, 0, numCharsRead);
                }
                String result = sb.toString();

                System.out.println("*** BEGIN ***");
                System.out.println(result);
                System.out.println("*** END ***");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

我用这个其他程序得到了相同的结果:

public class Application {

    public static void main(String[] args) throws ClientProtocolException, IOException {


        DefaultHttpClient httpclient = new DefaultHttpClient();

         HttpHost target = new HttpHost("foo.com", 80, "http");
         HttpGet getRequest = new HttpGet("/developers/apps.json");

         HttpResponse httpResponse = httpclient.execute(target, getRequest);
         HttpEntity entity = httpResponse.getEntity();

    }
}

这里是 printStackTrace :

Base64 encoded auth string: cmljYXJkLm9sbGVAZ21hBWwuY25tOkljb17vZmNvaWwxMDA=
java.net.ConnectException: Connection refused: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:564)
    at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:395)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:530)
    at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:272)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:329)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:911)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1172)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
    at com.sigfox.tests.ConnectToUrlUsingBasicAuthentication.main(ConnectToUrlUsingBasicAuthentication.java:46)

尝试删除那些行

System.setProperty("http.proxyHost", PROXY_HOST);
System.setProperty("http.proxyPort", PROXY_PORT);

如果是代理问题会显示

注意区分 ProxyAuthentication 和 URI 认证。

这里有一个 uri 身份验证示例[如果您需要在 URI 上进行身份验证] :

        BASE64Encoder encoder = new BASE64Encoder();//import sun.misc.BASE64Encoder;
        String authString = name + ":" + password;
        String authStringEncoded = encoder.encode(authString.getBytes());
        setHeader("Authorization", "Basic " + authStringEncoded);

这用于代理身份验证[如果您需要通过代理上网]:

            BASE64Encoder encoder = new BASE64Encoder();
            String authString = name + ":" + password;
            String authStringEncoded = encoder.encode(authString.getBytes());
            setHeader("Proxy-Authorization", "Basic " + authStringEncoded);

或许,您也可以探测 Apache 实用程序以获得正确编码的用户名/密码

像这样的伪代码:

Header  auth_header=
 new DigestScheme().authenticate(new UsernamePasswordCredentials(authUser.asString(),
                                                                 authPwd.asString()),
                                                       commonsHttpRequest,
                                                       new BasicHttpContext());

之后,只是:

urlConnection.setRequestProperty("Authorization", auth_header.getValue());

初步看来,好像是代理认证错误。尝试使用 Apache HC 4.x、Apache document

检查它

如果您使用的是 windows 代理服务器,请尝试使用 NTLM 身份验证(第 4.7 节)

对于第一遍尝试通过添加授权 header(就像您在代码中所做的那样)进行抢先式身份验证,这样您就可以跳过 401 和身份验证周期。