java访问https网站的方法
我必须通过我的 java 代码访问 https 站点。但它返回 401 响应。我在下面包含了我的代码。
try {
URL u = new URL(url);
HttpURLConnection http = (HttpURLConnection)u.openConnection();
http.setAllowUserInteraction(true);
http.connect();
String userpassword = "HP:M0lveau";
byte[] encoded = Base64.encodeBase64(userpassword.getBytes());
String encodedAuthorization = new String(encoded);
http.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
InputStream is = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
return stringBuilder.toString();
} catch (IOException ioe) {
logger.debug("fetchDataFromServer:IOException");
return null;
}
请尽早提供帮助..提前致谢....
I have to access an https site through my java code. But it returns 401 response. I included my code below.
try {
URL u = new URL(url);
HttpURLConnection http = (HttpURLConnection)u.openConnection();
http.setAllowUserInteraction(true);
http.connect();
String userpassword = "HP:M0lveau";
byte[] encoded = Base64.encodeBase64(userpassword.getBytes());
String encodedAuthorization = new String(encoded);
http.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
InputStream is = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
return stringBuilder.toString();
} catch (IOException ioe) {
logger.debug("fetchDataFromServer:IOException");
return null;
}
Please help as early as possible.. Thanks in advance....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试在调用 connect() 之前设置授权标头
Try to set the Authorization header before the call to connect()
我明白了..这是我的代码。
MyAuthenticator 类
I got it.. This is my code.
The class MyAuthenticator
401响应表示该请求需要用户身份验证。查看此处寻求帮助
有类似
和然后使用
还要手动检查这些凭据在给定的 url 上是否正常工作。
另外查看这个很棒的教程
401 response means that the request requires user authentication. LOOK here for help
Have something like
and then use
Also check manually that these credentials are working fine on the given url.
Also See this great tutorial