以下我的代码工作正常。
但是为URL =“http://dadosabertos.rio.rj.gov.br/apiTransporte/apresentacao/rest/index.cfm/onibus/474”返回null。
这两个网址在webbrowser上运行良好。
这是我的代码:
public class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Log.w("TAG", "result: " + result);
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
Log.v("TAG", "inputStream: " + inputStream);
Log.e("TAG", "httpResponse.getEntity().getContentLength(): " + httpResponse.getEntity().getContentLength());
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("TAG", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
可能有什么不对?事先提前
答案 0 :(得分:0)
如果您正在对API或JSON进行网络请求,请查看VOLLEY
库。它使用起来非常简单,它可以为您处理排队,异步和缓存。例如:
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//DO WITH RESPONSE
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//CRAP ERROR
Log.e("Volley", error.toString());
}
});
queue.add(request);
严重如果您要请求JSON数据,请使用Volley,这样简单得多!这是JSON请求所需的所有代码,它还为Images或Strings提供了其他内置请求类型,甚至允许自定义类型。