Android-network communication framework Volley Usage Details

Source: Internet
Author: User

1 Volley sends a get request:

public void getJson() {String url = "http://"+host+":8080/web/json.jsp?username=xjs&password=123456";mQueue.add(new JsonObjectRequest(Method.GET, url, null,new Listener
 
  () {@Overridepublic void onResponse(JSONObject response) {Log.e(TAG, "response : " + response.toString());}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {String err = error.getMessage();Log.e(TAG, "err : " + err);}}));}
 

2 Volley sends a post request:

public void postJson() {String url = "http://"+host+":8080/web/json.jsp";StringRequest postRequest = new StringRequest(Request.Method.POST, url,new Response.Listener
 
  () {@Overridepublic void onResponse(String response) {// responseLog.d("Response", response);}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {// errorLog.d("Error.Response", error.getMessage());}}) {@Overrideprotected Map
  
    getParams() {Map
   
     params = new HashMap
    
     ();params.put("username", "xjs");params.put("password", "123456");return params;}};mQueue.add(postRequest);}
    
   
  
 

3 Volley:

public void getImage() {String imageUrl = "http://"+host+":8080/web/image.jsp";NetworkImageView view = (NetworkImageView) findViewById(R.id.network_image_view);view.setDefaultImageResId(android.R.drawable.ic_menu_rotate); view.setErrorImageResId(android.R.drawable.ic_delete); view.setImageUrl(imageUrl, new ImageLoader(mQueue, new BitmapLruCache(1024 * 4)));}

4 Volley sends an Https request and the source code needs to be modified:

protected HttpURLConnection createConnection(URL url) throws IOException {if (url.toString().toLowerCase(Locale.CHINA).startsWith("https")) {HTTPSTrustManager.allowAllSSL();}return (HttpURLConnection) url.openConnection();}//HTTPSTrustManager.java:public class HTTPSTrustManager implements X509TrustManager {private static TrustManager[] trustManagers;private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)throws java.security.cert.CertificateException {// To change body of implemented methods use File | Settings | File// Templates.}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)throws java.security.cert.CertificateException {// To change body of implemented methods use File | Settings | File// Templates.}public boolean isClientTrusted(X509Certificate[] chain) {return true;}public boolean isServerTrusted(X509Certificate[] chain) {return true;}@Overridepublic X509Certificate[] getAcceptedIssuers() {return _AcceptedIssuers;}public static void allowAllSSL() {HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String arg0, SSLSession arg1) {// TODO Auto-generated method stubreturn true;}});SSLContext context = null;if (trustManagers == null) {trustManagers = new TrustManager[] { new HTTPSTrustManager() };}try {context = SSLContext.getInstance("TLS");context.init(null, trustManagers, new SecureRandom());} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();}HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());}}

5 Volley needs to modify the source code to obtain the cookie returned by the server:

@ Overridepublic HttpResponse initiate mrequest (Request
 Request, Map
 
  
AdditionalHeaders) throws IOException, AuthFailureError {for (Entry
  
   
> Header: connection. getHeaderFields (). entrySet () {if (header. getKey ()! = Null) {String key = header. getKey (); List
   
    
Values = header. getValue (); if (key. repeated signorecase ("set-cookie") {StringBuilder cookieString = new StringBuilder (); for (String value: values) {cookieString. append (value ). append ("\ n"); // use \ n as the separator. The cookie should not contain the carriage return symbol} cookieString. deleteCharAt (cookieString. length ()-1); Header h = new BasicHeader (header. getKey (), cookieString. toString (); response. addHeader (h);} else {Header h = new BasicHeader (header. getKey (), values. get (0); response. addHeader (h) ;}}}// re-write parseNetworkResponse (): @ Overrideprotected Response in the request
    
     
ParseNetworkResponse (NetworkResponse response) {Response
     
      
SuperResponse = super. parseNetworkResponse (response); Map
      
        ResponseHeaders = response. headers; String rawCookies = responseHeaders. get ("Set-Cookie"); // set-cookie: JSESSIONID = response; Path =/otn BIGipServerotn = 2564030730.64545.0000; path =/String part1 = substring (rawCookies, "", ";"); String part2 = substring (rawCookies, "\ n", ";"); // The client needs cookie: JSESSIONID = D90B58454550B4D37C4B66A76BF27B93; BIGipServerotn = 2564030730.64545.0000; cookies = part1 + ";" + part2 + ";"; return superResponse ;}
      
     
    
   
  
 

6. When Volley sends a request, upload the cookie and rewrite getHeaders () in the request ():

@Overridepublic Map
 
  getHeaders() throws AuthFailureError {         if(cookies!= null && cookies.length() > 0){                   HashMap
  
            headers = newHashMap
   
    ();                   headers.put("Cookie",cookies);                   returnheaders;         }         returnsuper.getHeaders();}
   
  
 

7 Volley custom request:

public class ByteArrayRequest extends Request
 
  {private final Listener
  
    mListener;public ByteArrayRequest(int method, String url, Listener
   
     listener, ErrorListener errlistener) {super(method, url, errlistener);mListener = listener;}@Overrideprotected Response
    
      parseNetworkResponse(NetworkResponse response) {if(response == null){return null;}if(response.statusCode != HttpStatus.SC_OK){return null;}byte[] bytes = response.data;return Response.success(bytes, null);}@Overrideprotected void deliverResponse(byte[] response) {if(mListener != null){mListener.onResponse(response);}}}
    
   
  
 

8 Volley:

@Overridepublic RetryPolicy getRetryPolicy() {          RetryPolicyretryPolicy = new DefaultRetryPolicy(5000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);          returnretryPolicy; }

With an example of logging on to the Ministry of Railways 12306, the source code in: http://download.csdn.net/download/goldenfish1919/7029907

Ps: During the test, I used a local tomcat and packed it under asserts.

Refer:

Http://blog.csdn.net/xyz_lmn/article/details/12165391

Http://blog.csdn.net/xyz_lmn/article/details/12746581

Http://blog.csdn.net/xyz_lmn/article/details/12177005

Http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put

Overview: http://blog.csdn.net/t12x3456/article/details/9221611

Getting Started: http://blog.csdn.net/ttdevs/article/details/17566795

Custom request: http://blog.csdn.net/ttdevs/article/details/17586205

Source code analysis: http://blog.csdn.net/ttdevs/article/details/17764351

Send https request: http://blog.csdn.net/llwdslal/article/details/18052723

Construct cache: http://stackoverflow.com/questions/16682595/android-volley-imageloader-bitmaplrucache-parameter

Parsing server cookie: http://stackoverflow.com/questions/20702178/android-volley-access-http-response-header-fields,http://blog.csdn.net/hpb21/article/details/12163371

Upload cookie: http://stackoverflow.com/questions/17049473/how-to-set-custom-header-in-volley-request

Set timeout: http://stackoverflow.com/questions/17094718/android-volley-timeout

Bytes.


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.