解决com.android.volley.NoConnection error, java.io.InterruptedIOException

本文详细解析了在使用Volley库时,由于错误地调用request.start()方法导致的问题,并提供了正确的解决策略。通过取消所有与特定tag相关的请求,重新设置tag并添加新的请求对象,避免了不必要的初始化调用,从而有效解决了该问题。

使用了request.start(),所以才导致的问题。

public static void RequstGet_JSONObject() {
        request.cancelAll(tag);
        jsonObjectRequest.setTag(tag);
        request.add(jsonObjectRequest);
        request.start();
}

因为在volley在初始化RequestQueue时,已经调用了start方法。

public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}

解决方法:

去掉request.start(),即可。

public static void RequstGet_JSONObject() {
        request.cancelAll(tag);
        jsonObjectRequest.setTag(tag);
        request.add(jsonObjectRequest);
}
package com.example.kucun2.entity.data; import static android.content.ContentValues.TAG; import android.content.Context; import android.util.Log; import com.example.kucun2.R; import com.example.kucun2.entity.Information; import com.example.kucun2.function.MyAppFnction; import com.example.kucun2.function.TLSUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.Type; import java.util.Map; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.X509TrustManager; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; public class ApiClient { // 使用Volley、Retrofit或OkHttp实现以下方法 private static final Gson gson = new Gson(); private static OkHttpClient client; private static final String TAG = "ApiClient"; static { } public static <T, R> void post(String url, Information<T> requestData, ApiCallback<R> callback) { // 1. 构建请求体(JSON格式) String jsonRequest = ReflectionJsonUtils.toJson(requestData); RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonRequest); // 2. 创建POST请求 Request request = new Request.Builder() .url(url) .post(body) .build(); Log.d(TAG, "POST请求URL: " + url); Log.d(TAG, "请求数据: " + jsonRequest); // 3. 发送异步请求 client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "请求失败: " + e.getMessage()); if (callback != null) { callback.onError(-1, e.getMessage()); } } @Override public void onResponse(Call call, Response response) throws IOException { try (ResponseBody responseBody = response.body()) { if (!response.isSuccessful()) { Log.e(TAG, "服务器响应错误: " + response.code() + " - " + response.message()); if (callback != null) { callback.onError(response.code(), response.message()); } return; } // 4. 处理成功响应 String jsonResponse = responseBody.string(); Log.d(TAG, "服务器响应: " + jsonResponse); // 5. 解析为Information对象 // 注意:这里需要提前确定响应中data的类型(TypeToken) Type responseType = new TypeToken<Information<R>>() { }.getType(); Information<R> responseInfo = gson.fromJson(jsonResponse, responseType); if (callback != null) { callback.onSuccess(responseInfo); } } } }); } public static <T, R> void put(String url, Information<T> data, ApiCallback<T> callback) { String jsonRequest = ReflectionJsonUtils.toJson(data); RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonRequest); Request request = new Request.Builder() .url(url) .put(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "PUT request failed", e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful() && callback != null) { String json = response.body().string(); Type responseType = new TypeToken<Information<T>>(){}.getType(); Information<T> info = gson.fromJson(json, responseType); callback.onSuccess(info); } } }); } public static <R> void delete(String url, ApiCallback<R> callback) { Request request = new Request.Builder() .url(url) .delete() .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "DELETE request failed", e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful() && callback != null) { // 对于删除操作,通常返回空数据 callback.onSuccess(new Information<>(200, "Deleted", null)); } } }); } public static interface ApiCallback<T> { void onSuccess(Information<T> data); void onError(int statusCode, String error); } } E Sync failed for Chanpin_Zujian java.lang.NullPointerException: Attempt to invoke virtual method 'okhttp3.Call okhttp3.OkHttpClient.newCall(okhttp3.Request)' on a null object reference at com.example.kucun2.entity.data.ApiClient.post(ApiClient.java:58) at com.example.kucun2.entity.data.SynchronizableEntity.createToServer(SynchronizableEntity.java:133) at com.example.kucun2.entity.data.SynchronizableEntity.sync(SynchronizableEntity.java:110) at com.example.kucun2.entity.data.SynchronizableEntity.syncWithDependencies(SynchronizableEntity.java:302) at com.example.kucun2.entity.data.SynchronizedList.add(SynchronizedList.java:81)
06-16
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值