来自NPM json-server的GET数据抛出NetworkOnMainThreadException

时间:2015-09-08 08:07:18

标签: java android android-asynctask httpurlconnection networkonmainthread

我正在编写一个小应用程序,它应该从npm json-server获取数据。它引发了一个例外。我确实使用AsyncTask扩展了连接类,并在" doInBackground"中执行了代码。但它仍然会引发异常。请帮助我。

以下是代码:

import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Network extends AsyncTask <String, Void, String> {
    public String urlString = ("http://localhost:3000");

    @Override
    protected String doInBackground(String... params) {
        StringBuffer chaine = new StringBuffer("");
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agnet", "");
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.connect();

            InputStream inputStream = connection.getInputStream();

            BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while ((line = rd.readLine()) != null) {
                chaine.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();

        }
        return chaine.toString();
    }
}

logcat告诉:

  

android.os.NetworkOnMainThreadException               在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)               at java.net.InetAddress.lookupHostByName(InetAddress.java:418)               at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)               在java.net.InetAddress.getAllByName(InetAddress.java:215)               在com.android.okhttp.HostResolver $ 1.getAllByName(HostResolver.java:29)               在com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)               在com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)               在com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:361)               在com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)               在com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)               在com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)               在smoca.ch.kreagen.Network.doInBackground(Network.java:25)               在smoca.ch.kreagen.BackendMockup.getData(BackendMockup.java:11)               在smoca.ch.kreagen.FillRealm.initRealm(FillRealm.java:43)               在smoca.ch.kreagen.Fragments.HomeFragment.onCreateView(HomeFragment.java:42)               在android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)               在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)               在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)               在android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)               在android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)               在android.support.v4.app.FragmentManagerImpl $ 1.run(FragmentManager.java:458)               在android.os.Handler.handleCallback(Handler.java:739)               在android.os.Handler.dispatchMessage(Handler.java:95)               在android.os.Looper.loop(Looper.java:145)               在android.app.ActivityThread.main(ActivityThread.java:5832)               at java.lang.reflect.Method.invoke(Native Method)               在java.lang.reflect.Method.invoke(Method.java:372)               在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1399)               在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

我知道问题出在&#34; connection.connect();&#34;被调用因为它应该在主线程中。但不应该。正确?

问候约翰

1 个答案:

答案 0 :(得分:1)

    public class Network extends AsyncTask <String, Void, String> {
    public String urlString = ("http://localhost:3000");
    HttpURLConnection connection;
    URL url;
    StringBuffer chaine;

    @Override
    protected String doInBackground(String... params) {

    Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                chaine = new StringBuffer("");
        try {
            url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agnet", "");
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.connect();

            InputStream inputStream = connection.getInputStream();

            BufferedReader rd = new BufferedReader(new       InputStreamReader(inputStream));
            String line = "";
            while ((line = rd.readLine()) != null) {
                chaine.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();

        }
            }
        });
        thread.start();

        return chaine.toString();
    }
}