1

I am trying to get content from the website Socialcast which needs authentication. (First I do a HTTP Post with Basic Authentication and then I try a HTTP GET). I tried several codes, I receive this as "result":

[email protected]:demo Base64 encoded auth string: ZW1pbHlAc29jaWFsY2FzdC5jb206ZGVtbw== * BEGIN You are being redirected. END *

Here is the code for HTTP Basic Auth:

try {
        String webPage = "http://demo.socialcast.com";
        String name = "[email protected]";
        String password = "demo";

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

However, when I try to do a GET afterwards, it says unauthorized. The credentials are [email protected]/demo - those are provided by Socialcast Dev at the moment, as I also cannot access my own Socialcast instance.
Is this code wrong? How can I do it properly? BTW, I am using HttpClient 4.x.

0

2 Answers 2

2

Are you sending the credentials in each request? I think this is needed, otherwise the server does not have any other information to prove that you still are authorized to view other pages...

Sign up to request clarification or add additional context in comments.

1 Comment

It seems that you are being redirected to the HTTPS page, have you tried querying it directly?
0

I'm not sure why this question is tagged with when your example code doesn't use it. In fact, if you do use httpclient then you can get it to handle authentication for you quite easily, see here for the excellent tutorial.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.