Android OkHttp Tutorial

Source: Internet
Author: User

First introduce the simple use of okhttp:

    • A general GET request
    • General POST request
    • HTTP-based file upload
    • File download
    • Loading pictures
    • Support Request callback, return object, object collection directly
    • Support for session retention

In Android Studio, you can choose to add dependencies

compile ‘com.squareup.okhttp:okhttp:2.4.0‘
compile ‘com.squareup.okio:okio:1.5.0‘
(i) Http Get
//Create Okhttpclient object okhttpclient mokhttpclient =new Okhttpclient ();//Create a requestFinal Request Request =new Request.builder (). URL ("Https://github.com/hongyangAndroid"). Build ();//new Callcall call = Mokhttpclient.newcall (request);//Request Join Schedule Call.enqueue (New Callback () {@Override Publicvoid  onfailure (Request request, IOException e) {}  @ Override  public  void  onresponse ( final Response Response)  Span class= "Hljs-keyword" >throws ioexception { < Span style= "FONT-SIZE:16PX;" >//string htmlstr = Response.body (). String (); } }); 
Response.body (). String () get string
response.body (). Bytes () get binary byte array
Response.body (). ByteStream () get input stream
(ii) Http Post carrying parameters
Request request = buildMultipartFormRequest(        new File[]{file}, new String[]{fileKey}, null);FormEncodingBuilder builder = new FormEncodingBuilder(); builder.add("username","张鸿洋");Request request = new Request.Builder() .url(url) .post(builder.build()) .build(); mOkHttpClient.newCall(request).enqueue(new Callback(){});

Android OkHttp Tutorial

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