HttpClient client = new DefaultHttpClient();
String url = "http://maps.google.co.in/maps?q=restaurants&radius=5000&sll=23,72&output=json";
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream inputStream = response.getEntity().getContent();
}
else
{
Toast.makeText(getBaseContext(), "error....", Toast.LENGTH_LONG);
}
这是我的简单代码,
但它崩溃了我的应用程序。向我展示了NPE和未被捕获的异常。 任何人都可以帮我排除故障并解决这个问题。
答案 0 :(得分:0)
请尝试运行以下代码。
HttpGet getMethod = new HttpGet("http://maps.google.co.in/maps?q=restaurants&radius=5000&sll=23,72&output=json");
DefaultHttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(getMethod);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null)
{
InputStream inStream = entity.getContent();
result= convertStreamToString(inStream);
Log.i("------------------ Reulst",result);
}
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}