我正在尝试从需要身份验证的网站 Socialcast 获取内容。 (首先,我使用基本身份验证执行 HTTP Post,然后尝试 HTTP GET)。
我尝试了几个代码,我收到这个作为“结果”:
emily@socialcast.com:演示
Base64 编码的授权字符串:ZW1pbHlAc29jaWFsY2FzdC5jb206ZGVtbw==
* 开始
你正在 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。
最佳答案
您是否在每个请求中发送凭据?我认为这是有必要的,否则服务器没有任何其他信息来证明您仍然有权查看其他页面...
关于java - HTTP 基本身份验证 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14375980/