On okhttp installation and simple use in Android Studio

Source: Internet
Author: User

Google seems to be in the 6.0 version of the deletion of httpclient-related APIs, in view of Okhttp's reputation is quite good, introduce the installation and use of Okhttp: I. Install the user for Android studio in Project Structure--- >dependencies Click "+" to select the library dependency search page Okttp,okio Note: okhttp internal dependency Okio, do not forget to import Okio at the same time two. Usage (i) HTTP Get http Post 

Create Okhttpclient object, set timeout

1 New Okhttpclient.builder () 2         . ConnectTimeout (timeunit.seconds)3         . ReadTimeout (Ten, Timeunit.seconds)4          . Build ();


Get, POST request different settings are the same except for the request body and the request method

Let's start with a 2.x to 3.x change in the request body class for a POST request:

In 2.x, the class name is: Formencodingbuilder ()

Use Formencodingbuilder builder = new Formencodingbuilder ();
Builder.add ("username","name");

In 3.x, the class name is: Formbody, but the general use is requestbody requestbodypost = new Formbody.builder ()

It needs to be explained that Formbody is a requestbody subclass.

This article uses the 3.x version

1 //Request parameter: page=1&code=news&pagesize=20&parentid=0&type=12Requestbody Requestbodypost =NewFormbody.builder ()3. Add ("page", "1")4. Add ("Code", "News")5. Add ("PageSize", "20")6. Add ("ParentID", "0")7. Add ("Type", "1")8. build ();

The default request method is the Get method, which can be omitted by the. Get ().

1Request Request =NewRequest.builder ()2 . Get ()3 . URL (get_url)4 . Build ();5Request Requestpost =NewRequest.builder ()6 . URL (post_url)7 . Post (Requestbodypost)8. build ();

Then the request object is constructed to get a call object

1 //New Call2Call call =Mokhttpclient.newcall (request);3 //Request Join Schedule4Call.enqueue (NewCallback ()5         {6 @Override7 Public voidOnFailure (Request request, IOException e)8             {9             }Ten  One @Override A Public voidOnresponse (FinalResponse Response)throwsIOException -             { -//string htmlstr = Response.body (). String (); the             } -});

Several points to note:

    • The parameters of the Onresponse callback are response, generally, for example, we want to get the returned string, which can be obtained response.body().string() if you want to get the returned binary byte array, or response.body().bytes() if you want to get the returned InputStream, callresponse.body().byteStream()

    • The thread that Onresponse executes is not the UI thread, if you want to manipulate the control, or you need to manipulate the UI with Handler,runonuithread, etc.
(b) HTTP-based file upload

Uploading a file differs from a typical post request with parameters in the construction of the Requestbody

The builder and type of Requestbody is just the version, 2.x is called MultipartBuilder,3.x叫做MultipartBody.Builder() . When we need to do something like a form upload, we can use it to construct our requestbody. Take 3.x as an example here

1File File =NewFile (Environment.getexternalstoragedirectory (), "Balabala.mp4");2 if(!file.exists ()) {3Toast.maketext (mainactivity. This, "file does not exist", Toast.length_short). Show ();4}Else {5Requestbody filebody = requestbody.create (Mediatype.parse ("Application/octet-stream"), file);6 /*Version 2.x7 requestbody requestbody = new Multipartbuilder ()8 . Type (multipartbuilder.form)*/9Requestbody Requestbody =NewMultipartbody.builder ()Ten . SetType (multipartbody.form) One . Addpart (Headers.of ( A"Content-disposition",  -"Form-data; Name=\ "Username\" "),  -Requestbody.create (NULL, "CXC")) the/*. Addpart (Headers.of ( - "Content-disposition", - "Form-data; Name=\ "Mfile\";  - filename=\ "Wjd.mp4\" "), Filebody)*/ +. Addformdatapart ("Mfile", File.getname (), filebody) -. Addformdatapart ("thumb", File.getname (), +Requestbody.create (Mediatype.parse ("image/*"), (file)); A //Add additional parameters at . Addformdatapart (key, value); - . Build (); -····· }

Description

Submit JSON data,mediatype.  Parse("Application/json; Charset=utf-8 ");

Upload images, mediatype.parse ("image/*");

Commit string,mediatype.  Parse("Text/x-markdown; Charset=utf-8 ")

Upload file, Mediatype.parse ("Application/octet-stream")

addpart and Addformdatapart The method is essentially the same

Upload pictures through the above settings, MP3, small files are no problem.

Upload download with progress monitoring please refer to http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0904/3416.html

On okhttp installation and simple use in Android Studio

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.