Android third-party HTTP network support package Okhttp the basics of using tutorials _android

Source: Internet
Author: User
Tags connection pooling http request

The primary goal of Okhttp package design and implementation is efficiency. This is one of the important reasons to choose Okhttp. Okhttp provides support for the latest HTTP protocol version HTTP/2 and SPDY, which allows all requests made to the same host to share the same socket connection. If HTTP/2 and SPDY are not available, Okhttp uses connection pooling to use the connection to increase efficiency. Okhttp provides default support for GZIP to reduce the size of the transfer content. Okhttp also provides caching mechanisms for HTTP responses to avoid unnecessary network requests. When a network problem occurs, Okhttp automatically retries multiple IP addresses for one host.
(Okhttp's GitHub homepage: https://github.com/square/okhttp)
The task that the HTTP client is going to perform is simple, accepting the HTTP request and returning the response. Each HTTP request includes a Url,http method (such as a Get or POST), an HTTP header and the requested body content, and so on. The response of the HTTP request contains the status code (such as 200 or more), the HTTP header and the principal content of the response, and so on. Although the interaction pattern of the request and response is simple, there are still a lot of details to consider in the implementation. Okhttp will handle the requests received, such as adding additional HTTP headers. Similarly, okhttp may do some processing of the response before returning a response. For example, Okhttp can enable GZIP support. When the actual request is sent, the okhttp will add the HTTP header accept-encoding. After receiving the response from the server, Okhttp will do the decompression and return the result. If the status code for the HTTP response is redirect-related, Okhttp is automatically redirected to the specified URL for further processing. Okhttp also handles user authentication-related responses.

How to use
1.gradle

Compile ' com.squareup.okhttp:okhttp:2.4.0 '

2.Initial
It is recommended that you do all the work for a new entity.

Okhttpclient = new Okhttpclient ();
Okhttpclient.setconnecttimeout (timeunit.seconds);
Okhttpclient.setreadtimeout (Timeunit.seconds);

3.GET
Okhttp uses calls to abstract the process of sending HTTP requests and getting responses. A basic example of sending an HTTP request using Okhttp is given in the following code. First, you create an object of the Okhttpclient class, which is the portal using the okhttp. Next, you create a Request object that represents an HTTP request. You can quickly create a Request object by Request.builder this build help class. The URL of the Request is specified here as http://www.baidu.com. A Call object is then created from the Request object by means of a okhttpclient Newcall method, and then the Execute method is invoked to execute the call, resulting in the Response object representing the HTTP response. You can access the different content of the response by using different methods in the Response object. such as the headers method to obtain the HTTP header, the body method gets to the Responsebody object that represents the response principal content.
Okhttp the most basic HTTP request

public class Syncget {public
  static void Main (string[] args) throws IOException {
  okhttpclient client = new Okhtt Pclient ();

  Request Request = new Request.builder ()
      . URL ("http://www.baidu.com")
      . Build ();

  Response Response = client.newcall (Request). Execute ();
  if (!response.issuccessful ()) {
    throw new IOException ("Server-side error:" + response);
  }

  Headers responseheaders = Response.headers ();
  for (int i = 0; i < responseheaders.size (); i++) {
    System.out.println (responseheaders.name (i) + ":" + Responsehea Ders.value (i));

  System.out.println (Response.body (). String ());
  }


4.POST
with the foundation of the above get, we'll just drop in and look at the post:

Builde requestbody
requestbody formbody = new Formencodingbuilder (). Add ("
  name", "Cuber")
  . Add ("Age", "26 ")
  . Build ();

Request Request = new Request.builder ()
   . URL (URL)
   . Post (Requestbody)
   . Build ();

5.Send
bring in the request from the top build.

Response response = client.newCall(request).execute();//如果response回传是null, 就代表timeout或没有网络

Or you want to use callback ...
Response Response = client.newcall (Request). Enqueue (New Callback () {

  @Override public
  void OnFailure ( Request request, IOException e) {
    //timeout or no network 
    //attention! This is Backgroundthread
  }

  @Override public
    void Onresponse (Response Response) throws IOException {
    / /Success
    /attention! This is Backgroundthread
  }
});

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.