当我将okhttp与“入队”一起使用时,我得到了android.os.NetworkOnMainThreadException

问题描述 投票:0回答:1

我在本机脚本项目中使用okhttp。我使用enqueue发出请求。但有时我有android.os.NetworkOnMainThreadException

我在做什么错?

我在TypeScript中发送请求的代码:

public okhttpRequest(method: "get" | "post" | "put" | "delete", url: string, options?: {
        body?: string;
        headers?: { [name: string]: string; };
        params?: { [param: string]: string; };
        responseType?: "json";
    }): Observable<Object> {
        // build the request
        const builder = new okhttp3.Request.Builder();

        // method
        switch (method) {
            case "post":
                builder.post(this.createOkhttpRequestBody(options && options.body));
                break;
            case "put":
                builder.put(this.createOkhttpRequestBody(options && options.body));
                break;
            case "delete":
                builder.delete();
                break;
        }

        // headers
        if (options && options.headers) {
            Object.keys(options.headers).forEach(key => {
                builder.header(key, options.headers![key]);
            });
        }

        // URL and parameters
        if (options && options.params) {
            const urlBuilder = okhttp3.HttpUrl.parse(url).newBuilder();
            Object.keys(options.params).forEach(key => {
                urlBuilder.addQueryParameter(key, options.params![key]);
            });
            builder.url(urlBuilder.build().toString());

        } else {
            builder.url(url);
        }

        const request = builder.build();

        const response: Subject<Object> = new Subject(); 

        this.okhttp.newCall(request).enqueue(new okhttp3.Callback({
            onResponse: (call: okhttp3.Call, resp: okhttp3.Response): void => {
                try {
                    this.zone.run(() => {
                        console.log(resp.code());
                        const body = resp.body().string();
                        console.log(body);
                        resp.close();

                        if (this.isResponseOk(resp.code())) {
                            response.next(JSON.parse(body));
                            response.complete();
                        } else {
                            response.error(new HttpWrapperErrorResponse(resp.code(), resp.message()));
                        }
                    });
                } catch (err) {
                    console.log(err);
                    resp.close();
                    response.error(new HttpWrapperErrorResponse(0, err.message));
                }
            },

            onFailure: (call: okhttp3.Call, e: java.io.IOException): void => {
                this.zone.run(() => {
                    response.error(new HttpWrapperErrorResponse(0, e.getMessage()));
                });
            }
        }));

        return response;
    }

我的堆栈跟踪:

android.os.NetworkOnMainThreadException  android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1460)
java.net.SocketInputStream.read(SocketInputStream.java:169)
java.net.SocketInputStream.read(SocketInputStream.java:139)
okio.Okio$2.read(Okio.java:140)
okio.AsyncTimeout$2.read(AsyncTimeout.java:237)
okio.RealBufferedSource.indexOf(RealBufferedSource.java:354)
okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:226)
okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:220)
okhttp3.internal.http1.Http1Codec$ChunkedSource.readChunkSize(Http1Codec.java:466)
okhttp3.internal.http1.Http1Codec$ChunkedSource.read(Http1Codec.java:449)
okhttp3.internal.Util.skipAll(Util.java:207)
okhttp3.internal.Util.discard(Util.java:189)
okhttp3.internal.http1.Http1Codec$ChunkedSource.close(Http1Codec.java:487)
okio.RealBufferedSource.close(RealBufferedSource.java:468)
okhttp3.internal.Util.closeQuietly(Util.java:142)
okhttp3.ResponseBody.string(ResponseBody.java:178)
com.tns.Runtime.callJSMethodNative(Native Method)
com.tns.Runtime.access$2300(Runtime.java:34)
com.tns.Runtime$3.run(Runtime.java:1263)
android.os.Handler.handleCallback(Handler.java:808)
android.os.Handler.dispatchMessage(Handler.java:101)
android.os.Looper.loop(Looper.java:166)
android.app.ActivityThread.main(ActivityThread.java:742**strong text**5)
java.lang.reflect.Method.invoke(Native Method)
com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921

Solytion:

它帮助了我:

application.android.on('activityCreated', function activityCreated(args) {
    android.os.StrictMode.setThreadPolicy(android.os.StrictMode.ThreadPolicy.LAX)
})
android nativescript okhttp
1个回答
0
投票

[如果您在活动内部使用的是okhttp,而不是在获得响应后使用此方法

activity.this.runonUiThread(new Runnable{
    this.zone.run(() => {
                    console.log(resp.code());
                    const body = resp.body().string();
                    console.log(body);
                    resp.close();

                    if (this.isResponseOk(resp.code())) {
                        response.next(JSON.parse(body));
                        response.complete();
                    } else {
                        response.error(new HttpWrapperErrorResponse(resp.code(), resp.message()));
                    }

});

[如果不是使用此片段]

       requireActivty.runonUiThread(new RUnnable{
        this.zone.run(() => {
                    console.log(resp.code());
                    const body = resp.body().string();
                    console.log(body);
                    resp.close();

                    if (this.isResponseOk(resp.code())) {
                        response.next(JSON.parse(body));
                        response.complete();
                    } else {
                        response.error(new HttpWrapperErrorResponse(resp.code(), resp.message()));
                    }


});
© www.soinside.com 2019 - 2024. All rights reserved.