A tutorial on HTTP headers in Android using the Okhttp package _android

Source: Internet
Author: User
Tags throwable

The

HTTP Header processing
HTTP headers are an important part of HTTP requests and responses. Some HTTP headers need to be set when creating an HTTP request. After you have received the HTTP response, you will also need to parse the HTTP headers that are included with it. From the code's point of view, the HTTP header's data structure is map<string, list<string>> type. That is, there may be multiple values for each HTTP header. But most HTTP headers have only one value, and only a small portion of HTTP headers allow multiple values. Okhttp uses a simple way to differentiate between these two types, making the use of HTTP headers simpler.
When setting an HTTP header, use the header (name, value) method to set the unique value of the HTTP header. For the same HTTP header, calling the method multiple times overrides the previously set value. Use the AddHeader (name, value) method to add a new value for the HTTP header. When reading an HTTP header, use the header (name) method to read the most recent value of the HTTP header. If the HTTP header has only a single value, the value is returned, and if there are multiple values, the last value is returned. Use the Headers (name) method to read all the values of the HTTP headers.
The header method is used in the following code to set the value of the User-agent header and to add a Accept header value. When parsing, the header method is used to get a single value of the Server header, and the headers method is used to get all the values of the Set-cookie header.

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

  Request Request = new Request.builder ()
      . URL ("http://www.baidu.com")
      . Header ("User-agent", "My Super Agent")
      . AddHeader ("Accept", "text/html")
      . Build ();

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

  System.out.println (Response.header ("Server"));
  System.out.println (Response.headers ("Set-cookie"));
  }



synchronous Get (Sync get)
download a file, print out his head information as a string, and print out the response data body information.

The String () method is very convenient and efficient as a response data body for some small files. However, if you are downloading for some large files (larger than 1MB files), try to avoid using the String () method because he will load the entire text into memory. The preferred solution for this example is to process the data body as a stream of data.

 Private final Okhttpclient client = new Okhttpclient ();

 public void Run () throws Exception {
  Request request = new Request.builder ()
    . URL ("http://publicobject.com/ Helloworld.txt ")
    . Build ();

  Response Response = client.newcall (Request). Execute ();
  if (!response.issuccessful ()) throw new IOException ("Unexpected Code" + response);

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

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

Asynchronous get (asynchronous get)
download tasks in the worker thread and notify by callback when the response arrives. This callback waits for the response header to be ready to be sent, and the read response header information is still blocked. The current okhttp does not support asynchronous APIS to receive the processing part of the response body.

Private final Okhttpclient client = new Okhttpclient ();

 public void Run () throws Exception {
  Request request = new Request.builder ()
    . URL ("http://publicobject.com/ Helloworld.txt ")
    . Build ();

  Client.newcall (Request). Enqueue (New Callback () {
   @Override public void onfailure (Request request, IOException Throwable) {
    throwable.printstacktrace ();
   }

   @Override public void Onresponse (Response Response) throws IOException {
    if (!response.issuccessful ()) throw new IOE Xception ("Unexpected Code" + 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 ());
   }
  }
 

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.