com.android.volley.NetworkResponse Java Examples

The following examples show how to use com.android.volley.NetworkResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GsonRequest.java    From VolleyX with Apache License 2.0 6 votes vote down vote up
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
    if (mType == null && mJavaClass == null) return Response.error(new ParseError());
    try {
        String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        T parsedGSON = null;
        if (mType != null) {
            parsedGSON = mGson.fromJson(jsonString, mType);
        } else {
            parsedGSON = mGson.fromJson(jsonString, mJavaClass);
        }
        return Response.success(parsedGSON,
                HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JsonSyntaxException je) {
        return Response.error(new ParseError(je));
    }
}
 
Example #2
Source File: HttpHeaderParserTest.java    From device-database with Apache License 2.0 6 votes vote down vote up
@Test public void parseCaseInsensitive() {

        long now = System.currentTimeMillis();

        Header[] headersArray = new Header[5];
        headersArray[0] = new BasicHeader("eTAG", "Yow!");
        headersArray[1] = new BasicHeader("DATE", rfc1123Date(now));
        headersArray[2] = new BasicHeader("expires", rfc1123Date(now + ONE_HOUR_MILLIS));
        headersArray[3] = new BasicHeader("cache-control", "public, max-age=86400");
        headersArray[4] = new BasicHeader("content-type", "text/plain");

        Map<String, String> headers = BasicNetwork.convertHeaders(headersArray);
        NetworkResponse response = new NetworkResponse(0, null, headers, false);
        Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

        assertNotNull(entry);
        assertEquals("Yow!", entry.etag);
        assertEqualsWithin(now + ONE_DAY_MILLIS, entry.ttl, ONE_MINUTE_MILLIS);
        assertEquals(entry.softTtl, entry.ttl);
        assertEquals("ISO-8859-1", HttpHeaderParser.parseCharset(headers));
    }
 
Example #3
Source File: HttpHeaderParserTest.java    From volley with Apache License 2.0 6 votes vote down vote up
@Test
public void parseCaseInsensitive() {
    long now = System.currentTimeMillis();

    List<Header> headers = new ArrayList<>();
    headers.add(new Header("eTAG", "Yow!"));
    headers.add(new Header("DATE", rfc1123Date(now)));
    headers.add(new Header("expires", rfc1123Date(now + ONE_HOUR_MILLIS)));
    headers.add(new Header("cache-control", "public, max-age=86400"));
    headers.add(new Header("content-type", "text/plain"));

    NetworkResponse response = new NetworkResponse(0, null, false, 0, headers);
    Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

    assertNotNull(entry);
    assertEquals("Yow!", entry.etag);
    assertEqualsWithin(now + ONE_DAY_MILLIS, entry.ttl, ONE_MINUTE_MILLIS);
    assertEquals(entry.softTtl, entry.ttl);
    assertEquals(
            "ISO-8859-1", HttpHeaderParser.parseCharset(HttpHeaderParser.toHeaderMap(headers)));
}
 
Example #4
Source File: StringRequest.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    String parsed;
    try {
        /*
         * 1. HttpHeaderParser 解析编码集
         * 2. 将请求结果 Response 的数据 ( data )通过编码集实例化一个数据 ( data ) String 类型
         */
        parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
    } catch (UnsupportedEncodingException e) {
        // 出现编码异常,就不进行编码处理,直接实例化一个 String
        parsed = new String(response.data);
    }
    /*
     * 解析成功,没有异常
     * 1. 将保存好 通过编码解析的 String 数据 返回
     * 2. 再通过 HttpHeaderParser 从网络请求回来的请求结果 NetworkResponse 的 Header 中提取出一个用于缓存的 Cache.Entry
     */
    return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
 
Example #5
Source File: ImageRequestTest.java    From volley with Apache License 2.0 6 votes vote down vote up
private void verifyResize(
        NetworkResponse networkResponse,
        int maxWidth,
        int maxHeight,
        ScaleType scaleType,
        int expectedWidth,
        int expectedHeight) {
    ImageRequest request =
            new ImageRequest("", null, maxWidth, maxHeight, scaleType, Config.RGB_565, null);
    Response<Bitmap> response = request.parseNetworkResponse(networkResponse);
    assertNotNull(response);
    assertTrue(response.isSuccess());
    Bitmap bitmap = response.result;
    assertNotNull(bitmap);
    assertEquals(expectedWidth, bitmap.getWidth());
    assertEquals(expectedHeight, bitmap.getHeight());
}
 
Example #6
Source File: ResponseTest.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Test public void publicMethods() throws Exception {
    // Catch-all test to find API-breaking changes.
    assertNotNull(Response.class.getMethod("success", Object.class, Cache.Entry.class));
    assertNotNull(Response.class.getMethod("error", VolleyError.class));
    assertNotNull(Response.class.getMethod("isSuccess"));

    assertNotNull(Response.Listener.class.getDeclaredMethod("onResponse", Object.class));

    assertNotNull(Response.ErrorListener.class.getDeclaredMethod("onErrorResponse",
            VolleyError.class));

    assertNotNull(NetworkResponse.class.getConstructor(int.class, byte[].class, Map.class,
            boolean.class, long.class));
    assertNotNull(NetworkResponse.class.getConstructor(int.class, byte[].class, Map.class,
            boolean.class));
    assertNotNull(NetworkResponse.class.getConstructor(byte[].class));
    assertNotNull(NetworkResponse.class.getConstructor(byte[].class, Map.class));
}
 
Example #7
Source File: ResponseTest.java    From volley with Apache License 2.0 6 votes vote down vote up
@Test
public void publicMethods() throws Exception {
    // Catch-all test to find API-breaking changes.
    assertNotNull(Response.class.getMethod("success", Object.class, Cache.Entry.class));
    assertNotNull(Response.class.getMethod("error", VolleyError.class));
    assertNotNull(Response.class.getMethod("isSuccess"));

    assertNotNull(Response.Listener.class.getDeclaredMethod("onResponse", Object.class));

    assertNotNull(
            Response.ErrorListener.class.getDeclaredMethod(
                    "onErrorResponse", VolleyError.class));

    assertNotNull(
            NetworkResponse.class.getConstructor(
                    int.class, byte[].class, Map.class, boolean.class, long.class));
    assertNotNull(
            NetworkResponse.class.getConstructor(
                    int.class, byte[].class, Map.class, boolean.class));
    assertNotNull(NetworkResponse.class.getConstructor(byte[].class));
    assertNotNull(NetworkResponse.class.getConstructor(byte[].class, Map.class));
}
 
Example #8
Source File: BulkDownloadService.java    From odyssey with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void fetchVolleyError(final ArtworkRequestModel model, final Context context, final VolleyError error) {
    if (BuildConfig.DEBUG) {
        Log.e(TAG, "VolleyError for request: " + model.getLoggingString());
    }

    if (error != null) {
        NetworkResponse networkResponse = error.networkResponse;
        if (networkResponse != null && networkResponse.statusCode == 503) {
            finishedLoading();
            return;
        }
    }

    ImageResponse imageResponse = new ImageResponse();
    imageResponse.model = model;
    imageResponse.image = null;
    imageResponse.url = null;
    new InsertImageTask(context, this).execute(imageResponse);
}
 
Example #9
Source File: ResponseTest.java    From device-database with Apache License 2.0 6 votes vote down vote up
@Test
public void publicMethods() throws Exception {
    // Catch-all test to find API-breaking changes.
    assertNotNull(Response.class.getMethod("success", Object.class, Cache.Entry.class));
    assertNotNull(Response.class.getMethod("error", VolleyError.class));
    assertNotNull(Response.class.getMethod("isSuccess"));

    assertNotNull(Response.Listener.class.getDeclaredMethod("onResponse", Object.class));

    assertNotNull(Response.ErrorListener.class.getDeclaredMethod("onErrorResponse",
            VolleyError.class));

    assertNotNull(NetworkResponse.class.getConstructor(int.class, byte[].class, Map.class,
            boolean.class, long.class));
    assertNotNull(NetworkResponse.class.getConstructor(int.class, byte[].class, Map.class,
            boolean.class));
    assertNotNull(NetworkResponse.class.getConstructor(byte[].class));
    assertNotNull(NetworkResponse.class.getConstructor(byte[].class, Map.class));
}
 
Example #10
Source File: MockNetwork.java    From device-database with Apache License 2.0 5 votes vote down vote up
@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    if (mNumExceptionsToThrow > 0 || mNumExceptionsToThrow == ALWAYS_THROW_EXCEPTIONS) {
        if (mNumExceptionsToThrow != ALWAYS_THROW_EXCEPTIONS) {
            mNumExceptionsToThrow--;
        }
        throw new ServerError();
    }

    requestHandled = request;
    return new NetworkResponse(mDataToReturn);
}
 
Example #11
Source File: JsonRequestCharsetTest.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@Test public void specifiedCharsetJsonArray() throws Exception {
    byte[] data = jsonArrayString().getBytes(Charset.forName("ISO-8859-2"));
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json; charset=iso-8859-2");
    NetworkResponse network = new NetworkResponse(data, headers);
    JsonArrayRequest arrayRequest = new JsonArrayRequest("", null, null);
    Response<JSONArray> arrayResponse = arrayRequest.parseNetworkResponse(network);

    assertNotNull(arrayResponse);
    assertTrue(arrayResponse.isSuccess());
    assertEquals(TEXT_VALUE, arrayResponse.result.getString(TEXT_INDEX));
    // don't check the copyright symbol, ISO-8859-2 doesn't have it, but it has Czech characters
}
 
Example #12
Source File: JsonRequestCharsetTest.java    From device-database with Apache License 2.0 5 votes vote down vote up
@Test public void specifiedCharsetJsonObject() throws Exception {
    byte[] data = jsonObjectString().getBytes(Charset.forName("ISO-8859-1"));
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json; charset=iso-8859-1");
    NetworkResponse network = new NetworkResponse(data, headers);
    JsonObjectRequest objectRequest = new JsonObjectRequest("", null, null, null);
    Response<JSONObject> objectResponse = objectRequest.parseNetworkResponse(network);

    assertNotNull(objectResponse);
    assertTrue(objectResponse.isSuccess());
    //don't check the text in Czech, ISO-8859-1 doesn't support some Czech characters
    assertEquals(COPY_VALUE, objectResponse.result.getString(COPY_NAME));
}
 
Example #13
Source File: JsonRequestCharsetTest.java    From device-database with Apache License 2.0 5 votes vote down vote up
@Test public void defaultCharsetJsonArray() throws Exception {
    // UTF-8 is default charset for JSON
    byte[] data = jsonArrayString().getBytes(Charset.forName("UTF-8"));
    NetworkResponse network = new NetworkResponse(data);
    JsonArrayRequest arrayRequest = new JsonArrayRequest("", null, null);
    Response<JSONArray> arrayResponse = arrayRequest.parseNetworkResponse(network);

    assertNotNull(arrayResponse);
    assertTrue(arrayResponse.isSuccess());
    assertEquals(TEXT_VALUE, arrayResponse.result.getString(TEXT_INDEX));
    assertEquals(COPY_VALUE, arrayResponse.result.getString(COPY_INDEX));
}
 
Example #14
Source File: JsonRequestCharsetTest.java    From device-database with Apache License 2.0 5 votes vote down vote up
@Test public void defaultCharsetJsonObject() throws Exception {
    // UTF-8 is default charset for JSON
    byte[] data = jsonObjectString().getBytes(Charset.forName("UTF-8"));
    NetworkResponse network = new NetworkResponse(data);
    JsonObjectRequest objectRequest = new JsonObjectRequest("", null, null, null);
    Response<JSONObject> objectResponse = objectRequest.parseNetworkResponse(network);

    assertNotNull(objectResponse);
    assertTrue(objectResponse.isSuccess());
    assertEquals(TEXT_VALUE, objectResponse.result.getString(TEXT_NAME));
    assertEquals(COPY_VALUE, objectResponse.result.getString(COPY_NAME));
}
 
Example #15
Source File: RequestTools.java    From BigApp_WordPress_Android with Apache License 2.0 5 votes vote down vote up
/***
     * 緩存的數據
     *
     * @param response
     * @param maxAge        缓存的有效时间,默认60秒
     * @param oldSoftExpire
     * @return
     */
    private Cache.Entry cache(NetworkResponse response, long maxAge, long oldSoftExpire) {
        long now = System.currentTimeMillis();
        if (maxAge == 0) maxAge = CACHE_MAXAGE;
//        (如果判断服务器是用的缓存的,还是从网络上获取的呢,当前时间与之前记录的时间对比?如果大于60秒则表示是新的么?可以有)
        long softExpire = now + maxAge * 1000;
        Log.e("", "wenjun request cache() oldSoftExpire - now = " + (oldSoftExpire - now) + ", oldSoftExpire = " + oldSoftExpire + ", softExpire = " + softExpire);
        if ((oldSoftExpire > now) && (oldSoftExpire < softExpire)) {
            //如果之前的时间一定大于现在的时间,并且之前的时间减去现在的时间如果在60秒内,则表示是同一个,不用再更新缓存了
            return null;
        }

        Map<String, String> headers = response.headers;

        long serverDate = 0;
        String serverEtag = null;
        String headerValue;

        headerValue = headers.get("Date");
        if (headerValue != null) {
            serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
        }
        Cache.Entry entry = new Cache.Entry();
        entry.data = response.data;
        entry.etag = serverEtag;
        entry.softTtl = softExpire;
        entry.ttl = entry.softTtl;
        entry.serverDate = serverDate;
        entry.responseHeaders = headers;
        return entry;
    }
 
Example #16
Source File: StringRequest.java    From device-database with Apache License 2.0 5 votes vote down vote up
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    String parsed;
    try {
        parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
    } catch (UnsupportedEncodingException e) {
        parsed = new String(response.data);
    }
    return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
 
Example #17
Source File: ImageRequest.java    From device-database with Apache License 2.0 5 votes vote down vote up
@Override
protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) {
    // Serialize all decode on a global lock to reduce concurrent heap usage.
    synchronized (sDecodeLock) {
        try {
            return doParse(response);
        } catch (OutOfMemoryError e) {
            VolleyLog.e("Caught OOM for %d byte image, url=%s", response.data.length, getUrl());
            return Response.error(new ParseError(e));
        }
    }
}
 
Example #18
Source File: JsonArrayRequest.java    From device-database with Apache License 2.0 5 votes vote down vote up
@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
        return Response.success(new JSONArray(jsonString),
                HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}
 
Example #19
Source File: RVImageRequest.java    From RestVolley with Apache License 2.0 5 votes vote down vote up
@Override
protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) {
    // Serialize all decode on a global lock to reduce concurrent heap usage.
    synchronized (sDecodeLock) {
        try {
            return doParse(response);
        } catch (OutOfMemoryError e) {
            VolleyLog.e("Caught OOM for %d byte image, url=%s", response.data.length, getUrl());
            return Response.error(new ParseError(e));
        }
    }
}
 
Example #20
Source File: RestVolleyRequest.java    From RestVolley with Apache License 2.0 5 votes vote down vote up
private String convertNetworkResponseData2String(NetworkResponse response, String encoding) throws IOException, ServerError {
    String content = new String();

    if (response == null) {
        return content;
    }

    byte[] datas;
    if (response instanceof StreamBasedNetworkResponse) {
        InputStream inputStream = ((StreamBasedNetworkResponse) response).inputStream;
        if (inputStream != null) {
            datas = StreamBasedNetwork.entityToBytes(inputStream, ((StreamBasedNetworkResponse) response).contentLength, RVNetwork.DEFAULT_POOL_SIZE);
        } else {
            datas = response.data;
        }
    } else {
        datas = response.data;
    }

    if (datas != null) {
        try {
            content = new String(datas, HttpHeaderParser.parseCharset(response.headers, encoding));
        } catch (Exception e) {
            content = new String(datas);
        }
    }

    return content;
}
 
Example #21
Source File: HTMobileClient.java    From live-app-android with MIT License 5 votes vote down vote up
@Override
protected Response<JsonObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String json = new String(
                response.data, HttpHeaderParser.parseCharset(response.headers));

        return Response.success(
                gson.fromJson(json, JsonObject.class), HttpHeaderParser.parseCacheHeaders(response));

    } catch (UnsupportedEncodingException | JsonSyntaxException e) {
        HTLogger.e(TAG, "parseNetworkResponse: ", e);
        ParseError parseError = new ParseError(response);
        return Response.error(parseError);
    }
}
 
Example #22
Source File: PatchRequest.java    From swaggy-jenkins with MIT License 5 votes vote down vote up
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
  String parsed;
  try {
    parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
  } catch (UnsupportedEncodingException e) {
    parsed = new String(response.data);
  }
  return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
 
Example #23
Source File: PutRequest.java    From swaggy-jenkins with MIT License 5 votes vote down vote up
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
  String parsed;
  try {
    parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
  } catch (UnsupportedEncodingException e) {
    parsed = new String(response.data);
  }
  return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
 
Example #24
Source File: PostRequest.java    From swaggy-jenkins with MIT License 5 votes vote down vote up
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
  String parsed;
  try {
    parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
  } catch (UnsupportedEncodingException e) {
    parsed = new String(response.data);
  }
  return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
 
Example #25
Source File: BingOAuth.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Used for debugging only to view verbose error information
 *
 * @param error the {@link VolleyError}
 */
private void verboseError(final VolleyError error) {

    final NetworkResponse response = error.networkResponse;

    if (response != null && error instanceof ServerError) {

        try {
            final String result = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            MyLog.i(CLS_NAME, "result: " + result);
        } catch (final UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
 
Example #26
Source File: CreateIDProfile.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Used for debugging only to view verbose error information
 *
 * @param error the {@link VolleyError}
 */
private void verboseError(@NonNull final VolleyError error) {

    final NetworkResponse response = error.networkResponse;

    if (response != null && error instanceof ServerError) {

        try {
            final String result = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            MyLog.i(CLS_NAME, "result: " + result);
        } catch (final UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
 
Example #27
Source File: FetchIDProfile.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Used for debugging only to view verbose error information
 *
 * @param error the {@link VolleyError}
 */
private void verboseError(@NonNull final VolleyError error) {

    final NetworkResponse response = error.networkResponse;

    if (response != null && error instanceof ServerError) {

        try {
            final String result = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            MyLog.i(CLS_NAME, "result: " + result);
        } catch (final UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
 
Example #28
Source File: ListIDProfiles.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Used for debugging only to view verbose error information
 *
 * @param error the {@link VolleyError}
 */
private void verboseError(@NonNull final VolleyError error) {

    final NetworkResponse response = error.networkResponse;

    if (response != null && error instanceof ServerError) {

        try {
            final String result = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            MyLog.i(CLS_NAME, "result: " + result);
        } catch (final UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
 
Example #29
Source File: FetchIDOperation.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Used for debugging only to view verbose error information
 *
 * @param error the {@link VolleyError}
 */
private void verboseError(@NonNull final VolleyError error) {

    final NetworkResponse response = error.networkResponse;

    if (response != null && error instanceof ServerError) {

        try {
            final String result = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            MyLog.i(CLS_NAME, "result: " + result);
        } catch (final UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
 
Example #30
Source File: DeleteIDProfile.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Used for debugging only to view verbose error information
 *
 * @param error the {@link VolleyError}
 */
private void verboseError(@NonNull final VolleyError error) {

    final NetworkResponse response = error.networkResponse;

    if (response != null && error instanceof ServerError) {

        try {
            final String result = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            MyLog.i(CLS_NAME, "result: " + result);
        } catch (final UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}