我正在实现针对Android的排球,但我得到了ClassCastException

时间:2014-05-08 07:29:40

标签: android android-volley

我正在调用Volley但是发生了ClassCast异常。下面我分享了代码。

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());            

//      StringRequest request = new StringRequest(Method.GET, "http://headers.jsontest.com/", listener, errorListener);

        String url = "http://echo.jsontest.com/key/value";

         JsonObjectRequest jsObjRequest = new JsonObjectRequest(url, null, listener, errorListener);
        requestQueue.add(jsObjRequest);

Response.Listener<JSONObject> listener = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d("","Success Response: " + response.toString()); 
        }
    };


    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (error.networkResponse != null) {
                Log.d("","Error Response code: " +  error.networkResponse.statusCode);
            }
        }
    };

为什么我会收到此异常以及如何解决此异常。

05-08 16:02:57.116: E/AndroidRuntime(16845): java.lang.ClassCastException: java.io.FileInputStream cannot be cast to java.io.ObjectInputStream
05-08 16:02:57.116: E/AndroidRuntime(16845):    at com.android.volley.toolbox.DiskBasedCache$CacheHeader.readHeader(DiskBasedCache.java:398)
05-08 16:02:57.116: E/AndroidRuntime(16845):    at com.android.volley.toolbox.DiskBasedCache.initialize(DiskBasedCache.java:157)
05-08 16:02:57.116: E/AndroidRuntime(16845):    at com.android.volley.CacheDispatcher.run(CacheDispatcher.java:85)

/**
         * Reads the header off of an InputStream and returns a CacheHeader object.
         * @param is The InputStream to read from.
         * @throws IOException
         */
        public static CacheHeader readHeader(InputStream is) throws IOException {
            CacheHeader entry = new CacheHeader();

            int magic = readInt(is);
            if (magic != CACHE_MAGIC) {
                // don't bother deleting, it'll get pruned eventually
                throw new IOException();
            }
            entry.key = readString(is);
            entry.etag = readString(is);
            if (entry.etag.equals("")) {
                entry.etag = null;
            }
            entry.serverDate = readLong(is);
            entry.ttl = readLong(is);
            entry.softTtl = readLong(is);
            **entry.responseHeaders = readStringStringMap((ObjectInputStream) is);**                                            return entry;
        }

代码中的斜体部分在Volley中错误的原因是错误的。

1 个答案:

答案 0 :(得分:0)

您获得的异常是因为您尝试将FileInputStream实例强制转换为ObjectInputStream,但这不是它的工作方式,您必须将其包装起来:

    final ObjectInputStream os = new ObjectInputStream(is);
    entry.responseHeaders = readStringStringMap(os);

例外情况表明您的is参数实际上是FileInputStream,但您无需处理:只需知道它是InputStream实现,所以您可以在ObjectInputStream构造函数中使用它。