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