Android-从URL加载json数据

Android-从URL加载json数据,android,json,url,download,Android,Json,Url,Download,我使用GoogleDirections API获取到位置之间的时间间隔,并尝试将数据从URL获取到JSON对象,以便我可以解析它以获得所需的数据。网址是: 我使用一个意图进入这个URL String url = "http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&

我使用GoogleDirections API获取到位置之间的时间间隔,并尝试将数据从URL获取到JSON对象,以便我可以解析它以获得所需的数据。网址是:

我使用一个意图进入这个URL

String url = "http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false"
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
这将在浏览器中显示json数据,我希望将其放入json对象中,以便使用以下方法获取所需的任何数据:

JSONObject durationObject = null; 
durationObject = jsonObject.getJSONObject("duration");
我已经在网上查过了,但我尝试的每一件事都失败了,或者不起作用。 下面是一些我尝试过但不起作用的代码。由于执行了if语句,所以没有任何内容会写入字符串结果

InputStream is = null;
String result = "";
JSONObject jsonObject = null;
try {   
    HttpClient httpclient = new DefaultHttpClient(); // for port 80 requests!
    HttpPost httppost = new HttpPost(url);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();

    // Read response to string
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),1024);
    StringBuilder sb = new StringBuilder();
    String line = "";
    while ((line = reader.readLine()) != null) {
    sb.append(line + "\n");
    }
    is.close();
    result = sb.toString(); 


    if (result.isEmpty()) { 
        result = "nothing"; 
        Toast msg = Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG);
    msg.show();
    }
 // Convert string to object

    jsonObject = new JSONObject(result);
这是logcat输出:

04-16 18:38:42.965: W/dalvikvm(9331): threadid=1: thread exiting with uncaught exception (group=0x40c371f8)
04-16 18:38:42.975: E/AndroidRuntime(9331): FATAL EXCEPTION: main
04-16 18:38:42.975: E/AndroidRuntime(9331): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.MainActivity}: android.os.NetworkOnMainThreadException
04-16 18:38:42.975: E/AndroidRuntime(9331):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1968)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1993)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at android.app.ActivityThread.access$600(ActivityThread.java:127)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1159)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at android.os.Looper.loop(Looper.java:137)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at android.app.ActivityThread.main(ActivityThread.java:4507)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at java.lang.reflect.Method.invokeNative(Native Method)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at java.lang.reflect.Method.invoke(Method.java:511)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at dalvik.system.NativeStart.main(Native Method)
04-16 18:38:42.975: E/AndroidRuntime(9331): Caused by: android.os.NetworkOnMainThreadException
04-16 18:38:42.975: E/AndroidRuntime(9331):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at com.example.test.MainActivity.onCreate(MainActivity.java:93)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at android.app.Activity.performCreate(Activity.java:4465)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
04-16 18:38:42.975: E/AndroidRuntime(9331):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1932)
04-16 18:38:42.975: E/AndroidRuntime(9331):     ... 11 more

我正在研究它,它似乎与启用严格模式有关。关于如何解决此问题的任何帮助都将非常有用。

这是我正在使用的工作代码

    private DefaultHttpClient httpclient = new DefaultHttpClient();

    public JSONObject getObjectInfo(String requestURL) throws Exception {

    JSONObject responseObject = null;
    Log.d(getClass().getSimpleName(), "HttpClient: getObjectInfo: "
            + requestURL);
    HttpGet httpget = new HttpGet(requestURL);
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        Log.d(getClass().getSimpleName(), "HttpClient: getObjectInfo: "
                + "respondreceived");
        if (entity != null) {
            InputStream instream = entity.getContent();
            Log.d("httpclient",
                    "HttpClient: getObjectInfo: converting to string");
            String jsonObjectString = Conversion
                    .convertStreamToString(instream);

            try {
                responseObject = new JSONObject(jsonObjectString);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalStateException e1) {
        e1.printStackTrace();
    } finally {

    }
    return responseObject;
}
用于将流转换为字符串的方法:

    public static String convertStreamToString(java.io.InputStream is) {

    try {
        return new java.util.Scanner(is).useDelimiter("\\A").next();
    } catch (java.util.NoSuchElementException e) {
        return "";
    }
}

因此,我建议使用Jakson库从接收到的json对象创建一个类。是一个如何使用Jakson库的示例。

这里发生的事情很常见,您试图在应用程序的主线程上执行一些长时间运行的操作

这意味着,主线程负责更新UI,以实现流畅的体验,如果android检测到您正在执行某个长时间运行的操作,而该操作将被阻止,它将强制关闭应用程序,让您知道这是不好的

有许多替代解决方案,如AsynTask或IntentService

IntentService是在向其发送意向时运行的服务:

public class NetworkHandler extends IntentService {
    @Override
    protected void onHandleIntent(Intent intent) {
         //Do what Saeid Farivar is saying here
    }
}
要激活IntentService,只需执行以下操作:

Intent intent = new Intent(mContext, NetworkHandler.class);
startService(intent);

你也可以发布日志吗?我也试过你的代码,但同样的事情发生了。应用程序崩溃了,我想这是因为严格的模式阻塞了主线程。尝试注释“意图代码”,硬编码谷歌api的url,并检查url是否获得数据。还要检查,您是否在manifest.ini中拥有internet权限。@homes请检查[this]()以了解主线程上的网络内容。感谢您解释此问题并提供其他解决方案建议。我使用了asynctask,并在doInBackground函数中实现了json的查询/解析,效果很好。