我试图从网站上访问一些json数据。它具有基本身份验证,因此我无法访问数据并收到异常:Filenotfoundexception。我现在正走在正确的道路上,但我需要最后一步的帮助。我的代码是:
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";
String webURL = "https://" + credentials + "@---";
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("HTTP_Authorization", "basic" + credentials);
connection.connect();
InputStream stream = connection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(stream));
//StringBuffer buffer = new StringBuffer();
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("coord", coord);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
我知道这段代码足以建立与任何其他JSON数据的连接,但由于那里的基本身份验证似乎无法连接到这个网站的json。我事先感谢你的帮助!