Java 使用 URLConnection 进行 HTTP 基本身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19644908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:05:37  来源:igfitidea点击:

HTTP Basic Authentication With URLConnection

javaandroidhttpurlconnectionbasic-authentication

提问by CodeDecode

connection = (HttpURLConnection)new URL(mURL).openConnection();
connection.setRequestMethod("GET");
String basicAuth = params[0] + ":" + params[1];
basicAuth = "Basic " + new String(Base64.encode(basicAuth.getBytes(),Base64.NO_WRAP));
connection.setRequestProperty("Authorization",basicAuth);
connection.connect();
InputStream in = connection.getInputStream();

I have gone through all possible questions based on this on SO but with out any success. I am trying to connect to my server using basic authentication. But when I try to access the input stream from URLConnectionit throws IOException. Thanks for any help from any one of you.

我已经在 SO 上基于此解决了所有可能的问题,但没有任何成功。我正在尝试使用基本身份验证连接到我的服务器。但是当我尝试从URLConnection它访问输入流时抛出IOException. 感谢你们中的任何人的任何帮助。

采纳答案by BudsNanKis

Basically, here there could be a few things that can go wrong. Does the URL you are trying to connect to exist? If not, may be you may have to redirect. Also, try

基本上,这里可能会出现一些问题。您尝试连接的 URL 是否存在?如果没有,可能是您可能需要重定向。另外,试试

connection.getResponseCode();

and make sure it returns 200 or HTTP_OK

并确保它返回 200 或 HTTP_OK

Needs more information to say anything. Go to debug mode and try to get the states of different objects used here.

需要更多信息才能说什么。进入调试模式并尝试获取此处使用的不同对象的状态。

Similar to IOException: "Received authentication challenge is null" (Apache Harmony/Android)

类似于IOException: "Received authentication challenge is null" (Apache Harmony/Android)