Search in sources :

Example 1 with NetworkResponse

use of com.android.volley.NetworkResponse in project IceNet by anton46.

the class NetworkManager method fromString.

private void fromString(final Map<String, String> headers, String requestTag, final RequestCallback requestCallback) {
    StringRequest request = new StringRequest(getUrlConnection(pathUrl), new Response.Listener<String>() {

        @Override
        public void onResponse(String s) {
            requestCallback.onRequestSuccess(s);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            if (requestCallback != null) {
                NetworkResponse response = error.networkResponse;
                if (response != null)
                    requestCallback.onRequestError(new RequestError(response));
            }
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return headers != null ? headers : super.getHeaders();
        }
    };
    networkHelper.addToRequestQueue(request, requestTag);
}
Also used : Response(com.android.volley.Response) NetworkResponse(com.android.volley.NetworkResponse) VolleyError(com.android.volley.VolleyError) StringRequest(com.android.volley.toolbox.StringRequest) NetworkResponse(com.android.volley.NetworkResponse)

Example 2 with NetworkResponse

use of com.android.volley.NetworkResponse in project IceNet by anton46.

the class NetworkManager method fromJsonArray.

private void fromJsonArray(final Map<String, String> headers, String requestTag, final RequestCallback requestCallback) {
    JsonArrayRequest request = new JsonArrayRequest(getUrlConnection(pathUrl), new Response.Listener<JSONArray>() {

        @Override
        public void onResponse(JSONArray jsonArray) {
            Object t = new Gson().fromJson(jsonArray.toString(), classTarget.getType());
            if (requestCallback != null)
                requestCallback.onRequestSuccess(t);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            if (requestCallback != null) {
                NetworkResponse response = error.networkResponse;
                if (response != null)
                    requestCallback.onRequestError(new RequestError(response));
            }
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return headers != null ? headers : super.getHeaders();
        }
    };
    networkHelper.addToRequestQueue(request, requestTag);
}
Also used : Response(com.android.volley.Response) NetworkResponse(com.android.volley.NetworkResponse) VolleyError(com.android.volley.VolleyError) JsonArrayRequest(com.android.volley.toolbox.JsonArrayRequest) JSONArray(org.json.JSONArray) NetworkResponse(com.android.volley.NetworkResponse) Gson(com.google.gson.Gson) JSONObject(org.json.JSONObject)

Example 3 with NetworkResponse

use of com.android.volley.NetworkResponse in project SimplifyReader by chentao0707.

the class BasicNetwork method performRequest.

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = Collections.emptyMap();
        try {
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                Entry entry = request.getCacheEntry();
                if (entry == null) {
                    return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, null, responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
                }
                // A HTTP 304 response does not have all header fields. We
                // have to use the header fields from the cache entry plus
                // the new ones from the response.
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
                entry.responseHeaders.putAll(responseHeaders);
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, entry.data, entry.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart);
            }
            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }
            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);
            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) ServerError(com.android.volley.ServerError) HttpResponse(org.apache.http.HttpResponse) AuthFailureError(com.android.volley.AuthFailureError) NetworkError(com.android.volley.NetworkError) NoConnectionError(com.android.volley.NoConnectionError) IOException(java.io.IOException) TimeoutError(com.android.volley.TimeoutError) StatusLine(org.apache.http.StatusLine) Entry(com.android.volley.Cache.Entry) SocketTimeoutException(java.net.SocketTimeoutException) NetworkResponse(com.android.volley.NetworkResponse) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 4 with NetworkResponse

use of com.android.volley.NetworkResponse in project FastDev4Android by jiangqqlmj.

the class HttpHeaderParserTest method parseCaseInsensitive.

@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));
}
Also used : Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) NetworkResponse(com.android.volley.NetworkResponse) BasicHeader(org.apache.http.message.BasicHeader) Cache(com.android.volley.Cache) Test(org.junit.Test)

Example 5 with NetworkResponse

use of com.android.volley.NetworkResponse in project FastDev4Android by jiangqqlmj.

the class ImageRequestTest method parseNetworkResponse_resizing.

@Test
public void parseNetworkResponse_resizing() throws Exception {
    // This is a horrible hack but Robolectric doesn't have a way to provide
    // width and height hints for decodeByteArray. It works because the byte array
    // "file:fake" is ASCII encodable and thus the name in Robolectric's fake
    // bitmap creator survives as-is, and provideWidthAndHeightHints puts
    // "file:" + name in its lookaside map. I write all this because it will
    // probably break mysteriously at some point and I feel terrible about your
    // having to debug it.
    byte[] jpegBytes = "file:fake".getBytes();
    ShadowBitmapFactory.provideWidthAndHeightHints("fake", 1024, 500);
    NetworkResponse jpeg = new NetworkResponse(jpegBytes);
    // Scale the image uniformly (maintain the image's aspect ratio) so that
    // both dimensions (width and height) of the image will be equal to or
    // less than the corresponding dimension of the view.
    ScaleType scalteType = ScaleType.CENTER_INSIDE;
    // Exact sizes
    // exactly half
    verifyResize(jpeg, 512, 250, scalteType, 512, 250);
    // just under half
    verifyResize(jpeg, 511, 249, scalteType, 509, 249);
    // larger
    verifyResize(jpeg, 1080, 500, scalteType, 1024, 500);
    // keep same ratio
    verifyResize(jpeg, 500, 500, scalteType, 500, 244);
    // Specify only width, preserve aspect ratio
    verifyResize(jpeg, 512, 0, scalteType, 512, 250);
    verifyResize(jpeg, 800, 0, scalteType, 800, 390);
    verifyResize(jpeg, 1024, 0, scalteType, 1024, 500);
    // Specify only height, preserve aspect ratio
    verifyResize(jpeg, 0, 250, scalteType, 512, 250);
    verifyResize(jpeg, 0, 391, scalteType, 800, 391);
    verifyResize(jpeg, 0, 500, scalteType, 1024, 500);
    // No resize
    verifyResize(jpeg, 0, 0, scalteType, 1024, 500);
    // Scale the image uniformly (maintain the image's aspect ratio) so that
    // both dimensions (width and height) of the image will be equal to or
    // larger than the corresponding dimension of the view.
    scalteType = ScaleType.CENTER_CROP;
    // Exact sizes
    verifyResize(jpeg, 512, 250, scalteType, 512, 250);
    verifyResize(jpeg, 511, 249, scalteType, 511, 249);
    verifyResize(jpeg, 1080, 500, scalteType, 1024, 500);
    verifyResize(jpeg, 500, 500, scalteType, 1024, 500);
    // Specify only width
    verifyResize(jpeg, 512, 0, scalteType, 512, 250);
    verifyResize(jpeg, 800, 0, scalteType, 800, 390);
    verifyResize(jpeg, 1024, 0, scalteType, 1024, 500);
    // Specify only height
    verifyResize(jpeg, 0, 250, scalteType, 512, 250);
    verifyResize(jpeg, 0, 391, scalteType, 800, 391);
    verifyResize(jpeg, 0, 500, scalteType, 1024, 500);
    // No resize
    verifyResize(jpeg, 0, 0, scalteType, 1024, 500);
    // Scale in X and Y independently, so that src matches dst exactly. This
    // may change the aspect ratio of the src.
    scalteType = ScaleType.FIT_XY;
    // Exact sizes
    verifyResize(jpeg, 512, 250, scalteType, 512, 250);
    verifyResize(jpeg, 511, 249, scalteType, 511, 249);
    verifyResize(jpeg, 1080, 500, scalteType, 1024, 500);
    verifyResize(jpeg, 500, 500, scalteType, 500, 500);
    // Specify only width
    verifyResize(jpeg, 512, 0, scalteType, 512, 500);
    verifyResize(jpeg, 800, 0, scalteType, 800, 500);
    verifyResize(jpeg, 1024, 0, scalteType, 1024, 500);
    // Specify only height
    verifyResize(jpeg, 0, 250, scalteType, 1024, 250);
    verifyResize(jpeg, 0, 391, scalteType, 1024, 391);
    verifyResize(jpeg, 0, 500, scalteType, 1024, 500);
    // No resize
    verifyResize(jpeg, 0, 0, scalteType, 1024, 500);
}
Also used : ScaleType(android.widget.ImageView.ScaleType) NetworkResponse(com.android.volley.NetworkResponse) Test(org.junit.Test)

Aggregations

NetworkResponse (com.android.volley.NetworkResponse)46 Test (org.junit.Test)20 HashMap (java.util.HashMap)17 Cache (com.android.volley.Cache)9 JSONObject (org.json.JSONObject)9 AuthFailureError (com.android.volley.AuthFailureError)8 NetworkError (com.android.volley.NetworkError)8 NoConnectionError (com.android.volley.NoConnectionError)8 ServerError (com.android.volley.ServerError)8 TimeoutError (com.android.volley.TimeoutError)8 JsonObjectRequest (com.android.volley.toolbox.JsonObjectRequest)8 IOException (java.io.IOException)8 MalformedURLException (java.net.MalformedURLException)8 SocketTimeoutException (java.net.SocketTimeoutException)8 ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)8 JSONArray (org.json.JSONArray)8 JsonArrayRequest (com.android.volley.toolbox.JsonArrayRequest)7 HttpResponse (org.apache.http.HttpResponse)7 StatusLine (org.apache.http.StatusLine)7 String (java.lang.String)6