尝试连接Socialcast API(演示)时,我收到401 Unauthorized。 这是我的代码:
ClientConnectionManager connectionManager = new BasicClientConnectionManager();
HttpClient client = new DefaultHttpClient(connectionManager);
HttpHost proxy = new HttpHost("myproxy", myport);
client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
Authenticator.setDefault(new MyAuthenticator("emily@socialcast.com", "demo"));
HttpGet httpGet = new HttpGet("https://demo.socialcast.com/api/authentication.xml".toString());
HttpResponse httpResponse = client.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
InputStream is = httpResponse.getEntity().getContent();
System.out.println(httpResponse.toString());
} else {
System.out.println(httpResponse.toString());
}
错误消息:
HTTP/1.1 401 Unauthorized [Server: nginx/1.0.14, Date: Thu, 17 Jan 2013 13:59:40 GMT,
Content-Type: application/xml; charset=utf-8, Transfer-Encoding: chunked,
Connection: keep-alive, Status: 401, X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 3.0.11,
WWW-Authenticate: Basic realm="Socialcast Email address/Password", X-Frame-Options: sameorigin, X-UA-Compatible: IE=Edge,chrome=1,
Cache-Control: no-cache, Set-Cookie: _socialcast_session=533602fb85f83dda3b9198a585f79961; path=/; secure; HttpOnly,
Set-Cookie: sct=2657f8e636d2c321e83748fae9223a994b2f5b7a1720d2282f7a; path=/; expires=Sat, 17-Jan-2015 13:59:40 GMT,
X-Request-Id: ee136acfaba474d376ecb1caceb6c055, X-Runtime: 0.010022, X-Rack-Cache: miss]
它出了什么问题?
答案 0 :(得分:0)
我解决了,这段代码有效:
System.setProperty("proxySet", "true");
System.setProperty("proxyHost", "myproxy");
System.setProperty("proxyPort", "myport");
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
System.out.printf("url=%s, host=%s, ip=%s, port=%s%n", getRequestingURL(),
getRequestingHost(), getRequestingSite(), getRequestingPort());
return new PasswordAuthentication("emily@socialcast.com", "demo".toCharArray());
}
});
URL url = new URL("https://demo.socialcast.com/api/users");
System.out.println(new Scanner(url.openStream()).useDelimiter("\\Z").next());