使用loopj SyncHttpClient时出现IOException

mik*_*r85 5 android loopj android-async-http

我需要在几个方面使用loopj的SyncHttpClient。当我使用AsyncHttpClient时,请求成功返回。当我按此处接受的答案所示使用SyncHttpClient时如何使用loopJ SyncHttpClient进行同步调用?,我在中遇到断点onFailure。该的StatusCode为0,错误响应是空的,抛出java.io.IOException异常:未处理的异常:空

这是相关的代码。再次,当我使用异步时,它工作正常:

        buttonTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                AsyncHttpClient httpClient = new AsyncHttpClient();
                SyncHttpClient httpClient = new SyncHttpClient();

                httpClient.get("http://10.0.1.6:3000/home/test_endpoint", new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        String stringResponse = response.toString();
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        String error = errorResponse.toString();
                    }
                });

                String temp = "got here";
            }
        });
Run Code Online (Sandbox Code Playgroud)

我正在使用 compile 'com.loopj.android:android-async-http:1.4.9'

mik*_*r85 1

您仍然必须从主线程运行它。这是对我有用的代码,它允许我在请求完成后命中设置在“String temp = 'got here'”的断点:

        buttonTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        AsyncHttpClient httpClient = new AsyncHttpClient();
                        SyncHttpClient httpClient = new SyncHttpClient();

                        httpClient.get("http://10.0.1.6:3000/home/test_endpoint", null, new JsonHttpResponseHandler() {
                            @Override
                            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                String stringResponse = response.toString();
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                                String error = errorResponse.toString();
                            }
                        });

                        String temp = "got here";
                    }
                }).start();
            }
Run Code Online (Sandbox Code Playgroud)

更多代码可以在他们的github页面上找到:https://github.com/loopj/android-async-http/blob/master/sample/src/main/java/com/loopj/android/http/sample/SynchronousClientSample.java