HTTP基本身份验证Java

时间:2013-01-17 09:35:50

标签: java http-basic-authentication

我正在尝试从需要身份验证的Socialcast网站获取内容。 (首先,我使用基本身份验证执行HTTP Post,然后尝试HTTP GET)。 我尝试了几个代码,我收到这个“结果”:     

emily@socialcast.com:演示     Base64编码的auth字符串:ZW1pbHlAc29jaWFsY2FzdC5jb206ZGVtbw ==      * BEGIN     你正在redirected。      结束*

以下是HTTP Basic Auth的代码:

try {
        String webPage = "http://demo.socialcast.com";
        String name = "emily@socialcast.com";
        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();
    }

然而,当我尝试之后进行GET时,它表示未经授权。 凭证是emily@socialcast.com/demo-这些是由Socialcast Dev提供的,因为我也无法访问我自己的Socialcast实例。
这段代码错了吗?我怎么能正确地做到这一点?顺便说一句,我使用的是HttpClient 4.x。

2 个答案:

答案 0 :(得分:2)

您是否在每个请求中发送凭据?我认为这是必要的,否则服务器没有任何其他信息来证明您仍然有权查看其他页面......

答案 1 :(得分:0)

我不确定当您的示例代码不使用时,为什么此问题会被标记。事实上,如果你确实使用了httpclient,那么你可以很容易地为它处理身份验证,see here for the excellent tutorial