Search code examples
javaurlauthenticationhttp-headersbasic-authentication

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


I am trying to connect to a website that requires a Basic authentication, but I get a java.net.ConnectException: Connection refused: connect and I can not get the content, the Basic authentication relies on a Base64 encoded 'Authorization' header whose value consists of the word 'Basic' followed by a space followed by the Base64 encoded name:password. And of course using the browser I get the proper json file I want

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

        }

I got same result with this other program:

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

    }
}

Here the 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)

Solution

  • Be carefull to difference ProxyAuthentication from URI authentication.

    Here you have an example for uri authentication [if u need to authenticate on the URI ] :

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

    This for proxy authentication [ if u need to go out internet though a proxy ]:

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

    Maybe, aslo, you can probe Apache utilities to get a correct encoded UserName / password

    Something like this pseudo code:

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

    After, just:

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