我有一个简单的Android代码,可以通过链接调用api:
class RetrieveDataTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected String doInBackground(Void... urls) {
String email = linkText.getText().toString();
// Get url from the Edittext
try {
URL url = new URL(linkText.getText().toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
statusCode = urlConnection.getResponseCode();
Log.d("RESPONSE_CODE", "doInBackground: " + statusCode);
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
}
}
对于某种api链接(请原谅我无法提供),JSON在浏览器上显示精美,但在Logcat中(&#34; Log.d&#34;命令) ),状态显示404(表示未找到!)。 这引出了一个关于编写从服务器请求数据的客户端应用程序的问题。如果服务器响应代码404或400(错误请求),或者当数据仍然显示在浏览器时,客户端应用程序是否仍然可以获取数据?
更新:调用API时我也看到了一些奇怪的行为。例如,在此链接上:
https://jsonplaceholder.typicode.com/photos
我现在变得疯狂了!