Simple use of okhttp

Source: Internet
Author: User

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 =NewOkhttpclient (); Request =NewRequest.builder (). URL (httpurl). build (); Call call = Okhttpclient.newcall (request);//Open asynchronous thread access networkCall.enqueue (NewCallback () {@Override             Public void Onresponse(Response Response)throwsIOException {String res = Response.body (). String (); Message msg =NewMessage ();                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();


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.;ImportJava.util.Map;ImportJava.util.Set;ImportJava.util.concurrent.TimeUnit;ImportCom.squareup.okhttp.Callback;ImportCom.squareup.okhttp.OkHttpClient;ImportCom.squareup.okhttp.Request;ImportCom.squareup.okhttp.Response;/** * Okhttp Package Tool class * * @author wangsong * * 2015-10-9 * * Public  class okhttputils {    Private Final StaticOkhttpclient m_ok_http_client =NewOkhttpclient ();Static{M_ok_http_client.setconnecttimeout ( -, timeunit.seconds); }/** * Do not open async thread * * @author wangsong 2015-10-9 * @param request * @return  * @throws ioexception * *     Public StaticResponseExecute(Request request)throwsIOException {returnM_ok_http_client.newcall (Request). Execute (); }/** * Open Asynchronous thread access, access results self-processing * * @author wangsong 2015-10-9 * @param request * @ Param Responsecallback * /     Public Static void Enqueue(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 * *     Public Static void Enqueue(Request request) {M_ok_http_client.newcall (Request). Enqueue (NewCallback () {@Override             Public void Onresponse(Response arg0)throwsIOException {}@Override             Public void onfailure(Request arg0, IOException arg1)    {            }        }); }/** * For HttpGet request stitching a parameter * * @author wangsong 2015-10-9 * @param URL * @param name * @param value * *     Public StaticStringJointurl(string URL, string name, String value) {returnURL +"?"+ name +"="+ value; }/** * Stitching multiple parameters for HttpGet request * * @author wangsong 2015-10-9 * @param URL * @param name * @param value * *     Public StaticStringJointurl(String URL, map<string, string> values) {StringBuffer result =NewStringBuffer (); Result.append (URL). Append ("?"); set<string> keys = Values.keyset (); for(String Key:keys) {result.append (key). Append ("="). Append (Values.get (key)). Append ("&"); }returnResult.tostring (). SUBSTRING (0, result.tostring (). Length ()-1); }}

This article relates to the tool class Https://

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. If there is a wrong place, I would appreciate it if I could criticize it.

Simple use of okhttp

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: 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.