Okhttp Easy to use

Source: Internet
Author: User

Simple use of okhttp

On the one hand, the recent discussion about Okhttp, on the other hand, I recently updated android6.0, found in 6.0 httpclient can not be used, so decided to take the time to see Okhttp, summed up a bit of things to share with you.

Before reading in school used on GitHub on an open source control asynchttpclient, at that time solved a lot of problems, upload pictures and download can achieve, feel good, this time to read Okhttp, There is no difference in functionality between the two (if any of the small partners found out can tell me).

The official website to okhttp the introduction or is more detailed, English good classmate can direct crossing the content of the net. With Okhttp We need the Okhttp jar package, and since Okhttp relies on Okio, we also need to download the Okio jar package. The two preparations are ready to begin.

One, send GET request

Request is a okhttp access, callback is a callback, there are two ways of calling One is Call.execute, this way does not open a new thread, to use this in Android need to open a new thread, and then call this thing in the thread, so instead of trouble, so the personal recommendation of using Call.enqueue,call.enqueue will open a new thread, in the new Calls a network request in a thread. That way we have to interact with the Android UI through handler.

Okhttpclient =new Okhttpclient ();        Request = new Request.builder (). URL (httpurl). build ();        Call call = Okhttpclient.newcall (request); //Open asynchronous Thread Access network Call.enqueue (new Callback () { @Override public void onresponse (Response respo NSE) throws IOException {string res = Response.body (). String (); Message msg = new Message (); msg.what = refreshdata; msg.obj = res; mhandler.sendmessage (msg);} @Override public void onfailure (Request arg0, IOException arg1) {}});     

Second, send the POST request

To send a POST request, one is to submit the JSON data:

MediaType JSON = MediaType.parse("application/json; charset=utf-8");        RequestBody body = RequestBody.create(JSON,                "{\"username\":\"lisi\",\"nickname\":\"李四\"}"); Request request = new Request.Builder().url(HTTPURL).post(body).build(); //后面的调用与GET相同

There is also a commit key-value pair:

RequestBody formBody = new FormEncodingBuilder()                .add("username", "lisi").add("nickname", "李四").build(); Request request = new Request.Builder().url(HTTPURL).post(formBody) .build();

Summarize

In fact, Okhttp compared to HttpURLConnection has been a lot simpler, but I still feel trouble, and the official also does not recommend that we create multiple okhttpclient instances, so it is a simple package.

Import java.io.IOException;Import Java.util.Map;Import Java.util.Set;Import Java.util.concurrent.TimeUnit;Import Com.squareup.okhttp.Callback;Import com.squareup.okhttp.OkHttpClient;Import Com.squareup.okhttp.Request;Import Com.squareup.okhttp.Response;/** * Okhttp Package Tool Class * *@author Wangsong * * 2015-10-9 * *PublicClassokhttputils {PrivateFinalstatic Okhttpclient m_ok_http_client =New Okhttpclient ();static {M_ok_http_client.setconnecttimeout ((Timeunit.seconds); }/** * Do not open async thread * *@author Wangsong 2015-10-9 *@param request *@return *@throws IOException * *PublicStatic ResponseExecute (Request request)Throws IOException {return M_ok_http_client.newcall (Request). Execute (); }/** * Open Asynchronous thread access, access results self-processing * *@author Wangsong 2015-10-9 *@param request *@param responsecallback * *PublicStaticvoidEnqueue (Request request, Callback Responsecallback) {m_ok_http_client.newcall (Request). Enqueue (Responsecallback);}/** * Open Asynchronous thread access, do not process access results * *@author Wangsong 2015-10-9 *@param request *@param responsecallback * *PublicStaticvoidEnqueue (Request request) {M_ok_http_client.newcall (Request). Enqueue (New Callback () {@OverridePublicvoidOnresponse (Response arg0)Throws IOException {}@OverridePublicvoidOnFailure (Request arg0, IOException arg1) {}}); }/** * Stitching a parameter for the httpget request * *@author Wangsong 2015-10-9 *@param URL *@param name *@param value */PublicStatic StringJointurl (string url, string name, String value) {Return URL +"?" + name +"=" + value; }/** * Stitching multiple parameters for HttpGet request * *@author wangsong 2015-10-9 * @param URL * @param name * @param value */public  static String  Jointurl (String URL, map<string, string> values) {stringbuffer result = new StringBuffer (); result.append (URL) . Append ("?"); set<string> keys = Values.keyset (); For (String key:keys) {result.append (key). Append ("="). Append (Values.get (key)). Append ("&");} return result.tostring (). Substring (0, result.tostring (). Length ()-1);}}      

This article relates to the tool class Https://github.com/lenve/OKHttpUtils

Okhttp Easy to use

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.