The Almighty Volley

Source: Internet
Author: User

V1olley capable of those things? Send a GET request

public void Getjson () {String URL = "//" +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);}));
Volley Send POST request:
public void Postjson () {String URL = "//" +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 ();p arams.put ("username", "XJS");p arams.put ("Password", " 123456 "); return params;}; Mqueue.add (postrequest);}
3.

Volley Get network pictures:

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 send HTTPS request, need to modify the source code:

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 Gets the cookie returned by the server and needs to modify the source code:

@Overridepublic HttpResponse performrequest (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.equalsignorecase ("Set-cookie")) {StringBuilder cookiestring = new StringBuilder (); for (String value:values) {cookiestring.append (value). Append ("\ n");//\ n As a delimiter, there should be no carriage return symbol in the cookie} 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);}}} Then rewrite the request in Parsenetworkresponse (): @Overrideprotected Response parsenetworkresponse (networkresponse Response) { Response superresponse = Super.parsenetworkresponse (Response); Map responseheaders = response.headers; String rawcookies = Responseheaders.get ("Set-cookie");//server return is SET-COOKIE:JSESSIONID=D90b58454550b4d37c4b66a76bf27b93; Path=/otn bigipserverotn=2564030730.64545.0000; path=/string part1 = substring (rawcookies, "", ";"); String part2 = substring (rawcookies, "\ n", ";"); /The client needs to be cookie:jsessionid=d90b58454550b4d37c4b66a76bf27b93; Bigipserverotn=2564030730.64545.0000;cookies = Part1 + ";" + Part2 + ";"; return superresponse;}

6 Volley upload a cookie when requested, rewrite Getheaders () in Request:

@Overridepublic Mapgetheaders () throws Authfailureerror {         if (cookies!= null && cookies.length () > 0) {                   HashMap         headers = Newhashmap ();                   Headers.put ("cookies", 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 set Request time-out:

@Overridepublic Retrypolicy Getretrypolicy () {          retrypolicyretrypolicy = new Defaultretrypolicy (5000, Defaultretrypolicy.default_max_retries, Defaultretrypolicy.default_backoff_mult);          Returnretrypolicy; }

Reprint: http://www.android100.org/html/201406/04/17036.html

About picture loading:

Requestqueue Mqueue = volley.newrequestqueue (context);
Imageloader Imageloader = new Imageloader (Mqueue, New Bitmapcache ());

Imagelistener listener = Imageloader.getimagelistener (Ivadvertise,
R.drawable.defaulto, R.drawable.error);//

Imageloader.get (head_img, Listener, 200, 200);

public class Bitmapcache implements Imagecache {

Private lrucache<string, bitmap> Mcache;

Public Bitmapcache () {
int maxSize = 10 * 1024 * 1024;
Mcache = new lrucache<string, bitmap> (maxSize) {

@Override
protected int sizeOf (String key, Bitmap value) {
TODO auto-generated Method Stub
return Value.getrowbytes () * Value.getheight ();
}
};
}

@Override
Public Bitmap getbitmap (String URL) {
TODO auto-generated Method Stub
return Mcache.get (URL);
}

@Override
public void Putbitmap (String URL, Bitmap BM) {
TODO auto-generated Method Stub
Mcache.put (URL, BM);
}
}

Wide height can not be set about

Networkdispatcher and see http://www.android100.org/html/201406/03/16240.html


The Almighty Volley

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.