尝试读取json文件时出现NetworkOnMainThreadException

时间:2017-10-25 05:17:47

标签: json httpclient

德国一起早上好!

我正在尝试从网络服务器读取一个小json文件。当我启动应用程序时,收到错误消息:android.os.NetworkOnMainThreadException

目标应该是,logcat显示我的json内容: 的 {"first":"one","second":"two"} Web服务器正在运行。当我访问:127.0.0.1/index.php时,浏览器显示我的上面一行。

这是我的主要:

package com.example.u0017007.jsonclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://127.0.0.1:80/index.php");
        StringBuilder stringBuilder = new StringBuilder();

        try {
            HttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));

                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }

                Log.i(this.getClass().getSimpleName(), stringBuilder.toString());
            } else {
                Log.e(this.getClass().getSimpleName(), "Fehler");
            }

        } catch (ClientProtocolException e) {
            Log.e(this.getClass().getSimpleName(), e.getMessage());

        } catch (IOException e) {
            Log.e(this.getClass().getSimpleName(), e.getMessage());
        }
    }
}

这是错误日志

 FATAL EXCEPTION: main
 Process: com.example.u0017007.jsonclient, PID: 16115
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u0017007.jsonclient/com.example.u0017007.jsonclient.MainActivity}: android.os.NetworkOnMainThreadException
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
     at android.app.ActivityThread.-wrap12(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6077)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
  Caused by: android.os.NetworkOnMainThreadException
     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:333)
     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
     at java.net.Socket.connect(Socket.java:586)
     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:149)
     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:366)
     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
     at com.example.u0017007.jsonclient.MainActivity.onCreate(MainActivity.java:29)
     at android.app.Activity.performCreate(Activity.java:6662)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
     at android.app.ActivityThread.-wrap12(ActivityThread.java) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
     at android.os.Handler.dispatchMessage(Handler.java:102) 
     at android.os.Looper.loop(Looper.java:154) 
     at android.app.ActivityThread.main(ActivityThread.java:6077) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756

1 个答案:

答案 0 :(得分:0)

您可以找到并使用相关问题,但为了向您提供可用解决方案的要点 - 您可以使用以下任何方法解决这些问题:

  • 您可以在主UI线程中禁止编写任何与网络相关的调用,但使用AsyncTask来实现您想要的内容。
  • 您还可以通过添加以下导入将以下代码添加到主文件中。

导入

    import android.os.StrictMode;

代码

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }