Okhttp Tool class for accessing the server using Get and post (i)

Source: Internet
Author: User

First of all, a brief introduction to the Okttp framework, similar to httpurlconnection,android6.0, abandoned the Apache Http Client, only HttpURLConnection and okhttp, relatively, Okhttp is becoming more and more popular with developers, so where is its advantage?

1, support Spdy, share the same socket to handle all requests of the same server
2, if the Spdy is not available, the connection pool is used to reduce the request delay
3, seamless support for gzip to reduce data traffic
4. Cache response data to reduce duplicate network requests

SPDY (read as "SPeeDY") is a TCP-based application-layer protocol developed by Google to minimize network latency, improve network speed, and optimize the user experience of network usage. Spdy is not a protocol to replace HTTP, but an enhancement to the HTTP protocol. Features of the new protocol include multiplexing of data streams, request prioritization, and HTTP header compression. Google said that after the introduction of the Spdy protocol, the page was loaded faster than the original 64% in lab testing.

The zip was originally created by Jean-loup Gailly and Mark Adler for file compression of the Unⅸ system. We often use files with the. gz suffix in Linux, which are in gzip format. Nowadays it has become a very popular data compression format, or a file format, used on the Internet.
GZIP encoding on the HTTP protocol is a technique used to improve the performance of Web applications. High-traffic Web sites often use gzip compression technology to make users feel faster. This generally refers to the WWW server installed in a feature, when someone to access the server's website, the server of this feature will compress the content of the Web page to be displayed in the browser of the visiting computer. Generally, the plain text content can be compressed to 40% of the original size. So the transmission is fast, The effect is that when you click on the URL, it will show up quickly. This, of course, also increases the load on the server. This function module is installed in the general server.

Reference: http://www.jianshu.com/p/7e25bb49c36c Pinterest Xu Xiao North

Okay, here's a look at encapsulation Class 1. Httpcallbacklistener
 Public  Interface   Httpcallbacklistener {    void  onfinish (String response);     void OnError (Exception e);}

2. Main body

ImportAndroid.util.Log;ImportCom.squareup.okhttp.Callback;ImportCom.squareup.okhttp.MediaType;Importcom.squareup.okhttp.OkHttpClient;Importcom.squareup.okhttp.Request;ImportCom.squareup.okhttp.RequestBody;ImportCom.squareup.okhttp.Response;ImportOrg.json.JSONObject;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.net.URL;ImportJava.net.URLEncoder;ImportJava.util.Map;/*** Created by Liang on 2016/8/15.*/ Public classOkhttputil { Public Static FinalMediaType json= Mediatype.parse ("Application/json; Charset=utf-8 ");  Public Static voidSendhttprequestforget (FinalString Path,FinalMap<string, string> params,FinalHttpcallbacklistener Listener) {        NewThread (NewRunnable () {@Override Public voidrun () {okhttpclient okhttpclient=Newokhttpclient (); Try {                    FinalStringBuilder Response_builder =NewStringBuilder (); FinalStringBuilder StringBuilder =NewStringBuilder (); Stringbuilder.append (Path). Append ("?"); if(Params! =NULL&& params.size ()! = 0) {                         for(Map.entry<string, string>Entry:params.entrySet ()) {                            //convert into UTF-8Stringbuilder.append (Entry.getkey ()). Append ("="). Append (Urlencoder.encode (Entry.getvalue (), "Utf-8")); Stringbuilder.append ("&"); }                        //Delete last character &Stringbuilder.deletecharat (Stringbuilder.length ()-1); }                    //The URL is longer, adding content from the mapURL url =NewURL (stringbuilder.tostring ()); Request Request=Newrequest.builder (). URL (URL). build (); //You must have an instantiated Object!!! Okhttpclient.newcall (Request). Enqueue (NewCallback () {@Override Public voidOnFailure (Request request, IOException e) {}//information such as Code,message,url can be obtained through response@Override Public voidOnresponse (Response Response)throwsIOException {//read the returned dataInputStream in =response.body (). ByteStream (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (In, "Utf-8"));                            String Line;  while(line = Reader.readline ())! =NULL) {response_builder.append (line); } LOG.E ("Okhttputil", response.tostring ()); //passing data into the mainactivity                            if(Listener! =NULL) {listener.onfinish (response_builder.tostring ());                }                        }                    }); } Catch(Exception e) {e.printstacktrace ();    }}). Start (); }     Public Static voidSendhttprequestforpost (FinalString Path,FinalMap<string, String> Paramsvalue,FinalHttpcallbacklistener Listener) {        NewThread (NewRunnable () {@Override Public voidrun () {okhttpclient okhttpclient=Newokhttpclient (); Try{                    FinalStringBuilder Response_builder =NewStringBuilder (); Jsonobject Jsonobject=NewJsonobject ();  for(map.entry<string,string>Entry:paramsValue.entrySet ())                    {Jsonobject.put (Entry.getkey (), Entry.getvalue ()); }                    //principal of the requestRequestbody requestbody=requestbody.create (json,jsonobject.tostring ()); Request Request=Newrequest.builder (). URL (path). Post (Requestbody). build (); //using the Async methodOkhttpclient.newcall (Request). Enqueue (NewCallback () {@Override Public voidOnFailure (Request request, IOException e) {LOG.E ("Okhttputil", "Response fail"); } @Override Public voidOnresponse (Response Response)throwsIOException {//read the returned dataInputStream in =response.body (). ByteStream (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (In, "Utf-8"));                            String Line;  while(line = Reader.readline ())! =NULL) {response_builder.append (line); } LOG.E ("Okhttputil", response.tostring ()); if(Listener! =NULL) {listener.onfinish (response_builder.tostring ());                }                        }                    }); }Catch(Exception e) {e.printstacktrace ();    }}). Start (); }}

This is just a small example, suitable for small white primer use.

Okhttp Tool class for accessing the server using Get and post (i)

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.