Android带Basic Authentication的JSON数据访问异常求助
修复Basic Authentication认证导致的请求失败问题
我帮你找到了代码里导致认证失败的两个关键问题,这也是你收到FileNotFoundException的核心原因(本质是服务器返回401未授权状态码,HttpsURLConnection会将这个错误映射为文件未找到异常):
问题1:请求头名称错误
你设置的请求头是HTTP_Authorization,但标准的Basic认证请求头名称应该是Authorization,这个错误会导致服务器无法识别你的认证信息。
问题2:认证凭证格式错误
你已经正确生成了Base64编码后的凭证credBase64,但并没有在请求头里使用它;而且Basic关键字后面必须加一个空格,再跟上编码后的凭证,而不是直接拼接原始的用户名密码字符串。
另外,虽然URL里拼接credentials@xxx的方式部分服务器支持,但这种方式会把凭证明文暴露在URL中,安全性较差,更推荐用请求头传递认证信息。
修正后的代码片段
下面是调整后的核心代码部分:
private class jsonConnection extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... voids) { String username = "---"; String password = "---"; String credentials = username + ":" + password; String sensorID = "sensors"; String api = "api"; // 移除URL里的凭证,改用请求头传递 String webURL = "https://---"; String credBase64 = Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT).replace("\n", ""); try { URL url = new URL(webURL + "/" + sensorID + "/" + api); System.out.println(url); System.out.println(credentials); connection = (HttpsURLConnection) url.openConnection(); connection.setUseCaches(false); connection.setReadTimeout(30000); connection.setConnectTimeout(30000); connection.setRequestMethod("GET"); connection.setDoInput(true); // 修正请求头:正确的名称+格式 connection.addRequestProperty("Authorization", "Basic " + credBase64); connection.connect(); // 可以先打印响应码,排查问题 int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); InputStream stream = connection.getInputStream(); bufferedReader = new BufferedReader(new InputStreamReader(stream)); String line = ""; while ((line = bufferedReader.readLine()) != null) { data = data + line; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
额外建议
- 测试时可以打印
responseCode,如果返回200说明认证成功;如果还是401,需要检查用户名密码是否正确,或者服务器是否要求其他额外的认证参数。 - 避免在代码里硬编码用户名密码,建议通过配置文件或者安全的方式存储这些敏感信息。
内容的提问来源于stack exchange,提问作者Buster3650
相关产品推荐
相关产品推荐

