当前位置: 首页 > 知识库问答 >
问题:

为什么我会出现这个错误?Android.os.NetworkonMaintHreadException

阮飞翔
2023-03-14

为什么会引发主线程上的网络异常?its在异步任务上

class JS extends AsyncTask<StringBuilder, Void, String>{

@Override
protected String doInBackground(StringBuilder... urlBuilder) {
    try {
        URL url = new URL(urlBuilder[0].toString());
        HttpURLConnection client = (HttpURLConnection) url.openConnection();
        client.setRequestProperty("accept", "application/json");
        InputStream in = client.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String returnString = br.readLine();
        client.disconnect();
        return returnString;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

}

编辑:

完整代码:


        package oliver;
    import android.os.AsyncTask;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import org.json.JSONTokener;

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;




    public class DrinkOrDriveWebService {

        private final static String DRINK_OR_DRIVE_WEB_SERVICE = "http://idrivedjango-env-qrs5vkxvvi.elasticbeanstalk.com/api/";

        /**
         * Constructor
         */
        List listOfBarUsers;
        List listOfPartyUsers;
        List listOfParties;
        List listOfPromotions;
        public static JS j = new JS();



        public DrinkOrDriveWebService() {
            listOfBarUsers = new ArrayList();
            listOfPartyUsers = new ArrayList();
            listOfParties = new ArrayList();
            listOfPromotions = new ArrayList();

        }

        public void parseBarUsers() {
            // CPSC 210 Students: You will need to complete this method
            // builds the URL to initialize session in the Waldo API 
            StringBuilder urlBuilder = new StringBuilder(DRINK_OR_DRIVE_WEB_SERVICE);
            urlBuilder.append("/baruser/");
            String input = j.doInBackground((urlBuilder));
            JSONArray obj;
            try {
                // parses the name, location, lat, lon, and timestamp of each Waldo generated
                obj = (JSONArray) (new JSONTokener(input).nextValue());
                System.out.println(obj.toString());
                if (obj.length() != 0) {
                    // For all Waldos generated
                    for (int i = 0, var = obj.length(); i getPartyUsers() {
            return this.listOfPartyUsers;
        }

        public List getBarUsers() {
            return this.listOfBarUsers;
        }

        public List getParties() {
            return this.listOfParties;
        }

        public List getPromos() {
            return this.listOfPromotions;
        }
        /**
         * Return the current list of Waldos that have been retrieved
         * 
         * @return The current Waldos
         */


        /**
         * Retrieve messages available for the user from the Waldo web service
         * 
         * @return A list of messages
         */


        /**
         * Execute a given query 
         * 
         * @param urlBuilder The query with everything but http:
         * @return The JSON returned from the query 
         */


    }
    class JS extends AsyncTask{

        @Override
        protected String doInBackground(StringBuilder... urlBuilder) {
            try {
                URL url = new URL(urlBuilder[0].toString());
                HttpURLConnection client = (HttpURLConnection) url.openConnection();
                client.setRequestProperty("accept", "application/json");
                String returnString = client.getResponseMessage();
                client.disconnect();
                return returnString;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

logcat:

03-16 11:01:27.375  23401-23401/com.example.untitled4 W/System.err﹕ android.os.NetworkOnMainThreadException
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at java.net.InetAddress.getAllByName(InetAddress.java:214)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseMessage(HttpURLConnectionImpl.java:499)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at oliver.JS.doInBackground(DrinkOrDriveWebService.java:288)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at oliver.DrinkOrDriveWebService.parseParty(DrinkOrDriveWebService.java:146)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.example.untitled4.mthr.doInBackground(mthr.java:20)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.example.untitled4.MyActivity.register(MyActivity.java:75)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.example.untitled4.MyActivity$1.onClick(MyActivity.java:51)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.view.View.performClick(View.java:4438)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.view.View$PerformClick.run(View.java:18422)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5017)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
03-16 11:01:27.385  23401-23401/com.example.untitled4 D/AndroidRuntime﹕ Shutting down VM
03-16 11:01:27.385  23401-23401/com.example.untitled4 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4194bba8)

共有2个答案

罗智志
2023-03-14

有关NetworkonMaintHreadExecption的更多信息。请参阅此问题

马星阑
2023-03-14

调用异步任务的方式不正确:

String input = j.doInBackground((urlBuilder));

您不应该自己调用doinbackground()。相反,创建异步任务类对象的一个新实例,并对其调用execute()。将结果捕获回onPostExecute()中的UI线程。

 类似资料:
  • 我正在尝试用Java制作一个与OpenGL(使用LWJGL 2)的窗口。当我尝试运行时,Eclipse BuiltInclassLoader出现了ClassNotFoundException错误。 我期望输出显示一个窗口,这是真正的输出: 线程“main”java.lang.noClassDeffounder中的异常错误:org/lwjgl/lwjglexception在enginetester.

  • 错误:第 1 行的解析错误:函数搜索(sour ^ 期望“字符串”、“数字”、“空”、“真”、“假”、“{”、“[”,得到“未定义” 代码:

  • 我实现了以下REST调用: 也是一个提供和使用application/x-protobuf的提供者类: 我的pom。xml看起来像: 我的小部件。原型: 选项java_package=“example”;选项java\u outer\u classname=“WidgetsProtoc”; 对于http://localhost:8080/RESTfulExample/widgets我得到以下错误消

  • 问题内容: 我已经阅读了 为什么在尝试在数据库中加载Blob时会出现java.lang.AbstractMethodError?,下载了我能找到的所有11g jdbc驱动程序,并将它们作为库和/或jar文件添加到了我的NetBeans应用程序中。我仍然不断收到相同的AbstractMethodError,这让我很生气!任何指导将不胜感激! 错误信息: 问题答案: 问题的原因是软件不兼容(jar文件

  • 我正在尝试使用Minikube、Docker注册表和演示节点项目创建本地库伯内特斯部署。 我做的第一件事是安装Docker v1.12.3,然后是Minikube v0.12.2。 然后,我通过运行这个命令创建了一个Docker注册表容器(通过本教程,只运行下面的第一个命令) 接下来,我运行这个minikube命令来创建本地kubernetes集群: 我的项目结构如下所示: 我的Dockerfil