Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从后台线程上的Okhttp3API调用获取空指针_Java_Android_Nullpointerexception_Okhttp3 - Fatal编程技术网

Java 从后台线程上的Okhttp3API调用获取空指针

Java 从后台线程上的Okhttp3API调用获取空指针,java,android,nullpointerexception,okhttp3,Java,Android,Nullpointerexception,Okhttp3,我正在开发一款使用web服务的移动应用程序。我使用的是MVP模式 有时,我在调试时得到响应,有时我得到一个空指针,指示后台线程在我尝试访问调用结果之前还没有完成对调用的处理 我如何解决这个问题?调用API的代码工作得很好,但这里的问题似乎是计时 登录交互程序类代码 OkHttpRequestUtil类的DoPost方法 公共类OkHttpRequestUtil{ public static final String TAG=OkHttpRequestUtil.class.getName(); O

我正在开发一款使用web服务的移动应用程序。我使用的是MVP模式

有时,我在调试时得到响应,有时我得到一个空指针,指示后台线程在我尝试访问调用结果之前还没有完成对调用的处理

我如何解决这个问题?调用API的代码工作得很好,但这里的问题似乎是计时

登录交互程序类代码

OkHttpRequestUtil类的DoPost方法

公共类OkHttpRequestUtil{
public static final String TAG=OkHttpRequestUtil.class.getName();
OkHttpClient mClient=null;
HttpResponseResult HttpResponseResult=null;
私人经理人;
公共HttpResponseResult DoPost(最终映射头、字符串postBody、上下文上下文、最终LoginInteractor.OnLoginFinishedListener侦听器、字符串url、MediaType jsonMediaType){
HttpUrl.Builder urlBuilder=HttpUrl.parse(url.newBuilder();
请求=null;
字符串processedUrl=urlBuilder.build().toString();
RequestBody=RequestBody.create(jsonMediaType,postBody);
mHandler=新处理程序(Looper.getMainLooper());
如果(标题!=null){
Headers headerBuild=Headers.of(Headers);
request=newrequest.Builder()
.标题(headerBuild)
.url(processedUrl)
.职位(机构)
.build();
}
其他的
{
request=newrequest.Builder()
.url(processedUrl)
.职位(机构)
.build();
}
试一试{
mClient=new-OkHttpClient.Builder()
.connectTimeout(30,时间单位为秒)
.readTimeout(30,时间单位为秒)
.writeTimeout(30,时间单位。秒)
.sslSocketFactory(CustomTrust.getPinnedCertSslSocketFactory(上下文),(X509TrustManager)CustomTrust.getTrustManagerFactory(上下文).GetTrustManager()[0])
.build();
}捕获(KeyStoreException e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}捕获(无算法异常){
e、 printStackTrace();
}捕获(证书例外e){
e、 printStackTrace();
}
mClient.newCall(request).enqueue(newcallback(){
@凌驾
公共void onFailure(调用调用,IOE异常){
call.cancel();
e、 printStackTrace();
}
@凌驾
public void onResponse(调用、最终响应)引发IOException{
//…在继续之前,请使用“isSuccessful”检查故障
如果(!response.issusccessful()){
Log.i(TAG,response.toString());
mHandler.post(新Runnable(){
@凌驾
公开募捐{
onPasswordError();
试一试{
抛出新IOException(“意外代码”+响应);
}捕获(IOE异常){
e、 printStackTrace();
}
}
});
}
//填充HttpResponseResult
httpResponseResult=新的httpResponseResult();
httpResponseResult.setCode(String.valueOf(response.code());
httpResponseResult.setMessage(response.message());
httpResponseResult.setBodyString(response.body().string());
Headers okHttpResponseHeaders=response.Headers();
Map responseHeadersTemp=新HashMap();
对于(int i=0;i
基本上,您的代码就像您的return语句发生在这个排队回调完成之前一样

mClient.newCall(request).enqueue
使HTTP响应为空,是的

一个解决方案是使
DoPost
不返回任何内容(请不要将方法名称大写)。使方法类型为
void

通过参数将
onResponse
的结果传回给
listener.onSuccess(responseData)


您可以立即解析响应,无需复制整个HTTP响应以及所有头文件

为什么要让异步方法等待结果?正确使用回调函数和监听器,那么在任何情况下都不应该为null。如果您真的想将okhttp与gson结合使用,我建议您尝试使用改型data@cricket_007,我采用这种方法是因为我希望尽可能地解耦应用程序组件。我还想创建一个okhttp3包装器,用于为API调用进行POST和GET操作。这很好,但是在任何异步代码中使用
return
这个词通常是非常困难的incorrect@cricket_007,这种方法可以很好地处理json数据。在我看来,使用OkHttp3比使用改型更直观。请以一种使我的关注点保持分离和解耦的方式,分享任何用于执行上述异步的示例代码。谢谢
public class OkHttpRequestUtil {
    public static final String TAG = OkHttpRequestUtil.class.getName();

    OkHttpClient mClient = null;
    HttpResponseResult httpResponseResult = null;
    private Handler mHandler;

    public HttpResponseResult DoPost(final Map<String, String> headers, String postBody, Context context, final LoginInteractor.OnLoginFinishedListener listener, String url, MediaType jsonMediaType) {

        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        Request request = null;
        String processedUrl = urlBuilder.build().toString();
        RequestBody body = RequestBody.create(jsonMediaType, postBody);

        mHandler = new Handler(Looper.getMainLooper());


        if (headers != null) {
            Headers headerBuild = Headers.of(headers);

            request = new Request.Builder()
                    .headers(headerBuild)
                    .url(processedUrl)
                    .post(body)
                    .build();

        }
        else
        {
            request = new Request.Builder()
                    .url(processedUrl)
                    .post(body)
                    .build();
        }


        try {
            mClient = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .sslSocketFactory(CustomTrust.getPinnedCertSslSocketFactory(context), (X509TrustManager) CustomTrust.getTrustManagerFactory(context).getTrustManagers()[0])
                    .build();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        }

        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                call.cancel();
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                // ... check for failure using `isSuccessful` before proceeding
                if (!response.isSuccessful()) {
                    Log.i(TAG, response.toString());
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            listener.onPasswordError();
                            try {
                                throw new IOException("Unexpected code " + response);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });



                }
                // Populate the HttpResponseResult

                httpResponseResult = new HttpResponseResult();
                httpResponseResult.setCode(String.valueOf(response.code()));
                httpResponseResult.setMessage(response.message());
                httpResponseResult.setBodyString(response.body().string());


                Headers okHttpResponseHeaders = response.headers();
                Map<String, String> responseHeadersTemp = new HashMap<String, String>();

                for(int i = 0; i < okHttpResponseHeaders.size(); i++)
                {
                    responseHeadersTemp.put(okHttpResponseHeaders.name(i), okHttpResponseHeaders.value(i));
                }

                httpResponseResult.setHeaders(responseHeadersTemp);

                listener.onSuccess();

            }
        });

        return httpResponseResult;
    }
}
mClient.newCall(request).enqueue