Use of Okhttp

Source: Internet
Author: User
Tags http post

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

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

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

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.