1. Add Dependencies:
compile ‘com.squareup.okhttp:okhttp:2.4.0‘
Note: Okhttp internally relies on Okio, don't forget to import Okio at the same time:
Gradlecompile ‘com.squareup.okio:okio:1.5.0‘
2.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 public void onfailure (Request request, IOException e) {} @Override public void onresponse (final Response Response) throws ioexception {// String htmlstr = Response.body (). String (); } });
/span>
The above is the step to send a GET request, first construct a request object, the parameter at least has a URL, of course you can set more parameters such as: header
, and method
so on Request.builder.
A Call object is then constructed from the request object, which is similar to encapsulating your requests as tasks, and since it is a task, there are execute()
ways to do cancel()
so.
Finally, we want to execute the request asynchronously, so we're calling Call.enqueue, adding call to the dispatch queue, and waiting for the task to finish, we can get the result in callback.
3.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(){});
Use of Okhttp