Explain the way Android uses Okhttp to send HTTP POST requests _android

Source: Internet
Author: User
Tags html file upload html file upload form http post

HTTP POST and put requests can contain content to be submitted. You only need to specify what you want to commit when you create the Request object by using the post and put methods.
Basic example of an HTTP POST request:

public class Poststring {public
  static void Main (string[] args) throws IOException {
  okhttpclient client = new Ok HttpClient ();
  MediaType Media_type_text = Mediatype.parse ("Text/plain");
  String postbody = "Hello World";

  Request Request = new Request.builder ()
      . URL ("http://www.baidu.com")
      . Post (Requestbody.create media_type_ TEXT, Postbody))
      . Build ();

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

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


Submitting content as String is only applicable to situations where the content is relatively small. When the content of the request is large, the stream should be used for submission.

Post Way to communicate

The

posts the submitting request body in a streaming manner. The content of the request body is generated by the stream write. This example is a stream that writes directly to the Okio Bufferedsink. Your program may use OutputStream, and you can use Bufferedsink.outputstream () to get it.

public static final MediaType Media_type_markdown = Mediatype.parse ("Text/x-markdown;

Charset=utf-8 ");

Private final Okhttpclient client = new Okhttpclient (); public void Run () throws Exception {requestbody requestbody = new Requestbody () {@Override public mediatype Contentty
  PE () {return media_type_markdown;
   @Override public void WriteTo (Bufferedsink sink) throws IOException {Sink.writeutf8 ("numbers\n");
   Sink.writeutf8 ("-------\ n");
   for (int i = 2; I <= 997 i++) {Sink.writeutf8 (String.Format ("*%s =%s\n", I, Factor (i)));
  } private String factor (int n) {for (int i = 2; i < n; i++) {int x = n/i;
   if (x * i = = N) return factor (x) + "x" + i;
  return integer.tostring (n);

 }
 };

 Request Request = new Request.builder (). URL ("Https://api.github.com/markdown/raw"). Post (Requestbody). build ();
 Response Response = client.newcall (Request). Execute (); if (!response.issuccessful ()) throw new IOException ("unexpectedCode "+ response);
System.out.println (Response.body (). String ());

 }

Post Method Submit File

The file as the request body is very simple.

public static final mediatype Media_type_markdown
 = Mediatype.parse ("Text/x-markdown; Charset=utf-8 ");

Private final Okhttpclient client = new Okhttpclient ();

public void Run () throws Exception {
 file File = new file ("Readme.md");

 Request Request = new Request.builder ()
   . URL ("Https://api.github.com/markdown/raw")
   . Post ( Requestbody.create (Media_type_markdown, file))
   . Build ();

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

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


Post mode submit a form

Use Formencodingbuilder to build a request body with the same effect as HTML <form> tags. A key-value pair is encoded using a URL encoding in HTML-compatible form.

Private final Okhttpclient client = new Okhttpclient ();

public void Run () throws Exception {
 requestbody formbody = new Formencodingbuilder ()
   . Add ("Search", "Jurassic Pa RK ")
   . Build ();
 Request Request = new Request.builder ()
   . URL ("https://en.wikipedia.org/w/index.php").
   post (formbody)
   . Build ();

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

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


Post method to commit a block request

Multipartbuilder can build complex request body, compatible with HTML file upload form. Each request in a multiple-block request body is a request body that can define its own request header. These request headers can be used to describe the request, such as his content-disposition. If Content-length and Content-type are available, they are automatically added to the request header.

private static final String imgur_client_id = "...";

Private static final mediatype media_type_png = Mediatype.parse ("Image/png");

Private final Okhttpclient client = new Okhttpclient (); public void Run () throws Exception {//Use the Imgur image upload API as documented at https://api.imgur.com/endpoints/i Mage requestbody requestbody = new Multipartbuilder (). Type (Multipartbuilder.form). Addpart (Headers.of ("Conte Nt-disposition "," form-data; Name=\ "Title\"), Requestbody.create (null, "Square Logo"). Addpart (Headers.of ("Content-disposition", "form- Data

 Name=\ "image\"), Requestbody.create (Media_type_png, New File ("Website/static/logo-square.png")). Build (); Request Request = new Request.builder () header ("Authorization", "Client-id" + imgur_client_id). URL ("https://api.i

 Mgur.com/3/image "). Post (Requestbody). build ();
 Response Response = client.newcall (Request). Execute (); if (!response.issuccessful ()) throw new IOException ("Unexpected Code "+ response);
System.out.println (Response.body (). String ());
 }

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.