Volley (5), an open-source android network framework, some details of volley

Source: Internet
Author: User

Volley (5), an open-source android network framework, some details of volley

Volley has been sorted out recently. Some minor problems that have not been encountered before come back. Here we record:


1. Unable to add body in HttpUrlConnection DELETE mode: java.net. ProtocolException: DELETE does not support writing


This can be regarded as a system-level bug. For more information, see here. This problem was solved only in Java 8. There is no way to go directly. Check HttpUrlConnection. We found that it is an abstract class. Therefore, we can try other implementations of HttpUrlConnection to achieve our goal. Finally, we decided to use the okhttp implementation. Address: https://github.com/square/okhttp.

Next, let's take a look at volley's source code. Because our app is compatible with a minimum version of 4.0, we know that HurlStack is called:

    public static RequestQueue newRequestQueue(Context context, HttpStack stack) {...        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));            }        }...    }

Therefore, we only need to modify the relevant code of HurlStack, as shown below:

Volley. java

public static RequestQueue newRequestQueue(Context context, HttpStack stack) {...        if (stack == null) {            if (Build.VERSION.SDK_INT >= 9) {                // old way: stack = new HurlStack();            // http://square.github.io/okhttp/                stack = new HurlStack(null, null, new OkUrlFactory(new OkHttpClient()));            } 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));            }        }...    }
HurlStack. java

/** * An {@link HttpStack} based on {@link HttpURLConnection}. */public class HurlStack implements HttpStack {    private final OkUrlFactory mOkUrlFactory;     /**     * @param urlRewriter Rewriter to use for request URLs     * @param sslSocketFactory SSL factory to use for HTTPS connections     * @param okUrlFactory solution delete body(https://github.com/square/okhttp)     */    public HurlStack(UrlRewriter urlRewriter, SSLSocketFactory sslSocketFactory, OkUrlFactory okUrlFactory) {        mUrlRewriter = urlRewriter;        mSslSocketFactory = sslSocketFactory;        mOkUrlFactory = okUrlFactory;    }    /**     * Create an {@link HttpURLConnection} for the specified {@code url}.     */    protected HttpURLConnection createConnection(URL url) throws IOException {if(null != mOkUrlFactory){return mOkUrlFactory.open(url);}        return (HttpURLConnection) url.openConnection();    }    @SuppressWarnings("deprecation")    /* package */     static void setConnectionParametersForRequest(HttpURLConnection connection,            Request
  request) throws IOException, AuthFailureError {        switch (request.getMethod()) {            ...            case Method.DELETE:                connection.setRequestMethod("DELETE");                addBodyIfExists(connection, request);                break;            ...            default:                throw new IllegalStateException("Unknown method type.");        }    }...}


2. About (modify) volley Cache


Volley has a complete cache mechanism. At present, we want to make a simple requirement: Some interfaces (almost unchanged) simply cache for a certain period of time, after studying the code, it is easy to modify it for your own purposes (volley's cache mechanism has time to be analyzed. This must be done ). To put it simply, modify the following content: In request. parseNetworkResponse

HttpHeaderParser ). The modified HttpHeaderParser code is as follows:

/*** After modification, the user processes the Cache */public class BHHttpHeaderParser {/*** Extracts a {@ link Cache. entry} from a {@ link NetworkResponse }. ** @ param response The network response to parse headers from * @ return a cache entry for the given response, or null if the response is not cacheable. */public static Cache. entry parseCacheHeaders (NetworkResponse response, boolean isCustomCache ){... if (isCustomCache) {softExpire = now + Config. HTTP_CACHE_TTL;} else {if (hasCacheControl) {softExpire = now + maxAge * 1000;} else if (serverDate> 0 & serverExpires> = serverDate) {// Default semantic for Expire header in HTTP specification is softExpire. softExpire = now + (serverExpires-serverDate) ;}} 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 ;}...}
We can find that we mainly decide how to modify the cache TTL based on custom variables to achieve our goal.


Other summary about volley will be recorded here later.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.