Okhttp is an efficient HTTP library:
Support SPDY, share the same Socket to handle all requests from the same server
If the SPDY is unavailable, the connection pool is used to reduce the request delay
Seamless support for gzip to reduce data traffic
Cache response data to reduce duplicate network requests
OkHttp handles a number of network problems: it automatically recovers from many common connectivity issues. If your server is configured with multiple IP addresses, Okhttp will automatically attempt the next IP when the first IP connection fails. Okhttp also handles proxy server issues and SSL handshake failure issues.
Okhttp is a relatively mature solution, it is said that the source of Android4.4 can see HttpURLConnection has been replaced by Okhttp realized. So we have more reason to believe that okhttp is strong.
1. HTTP request method
Private final okhttpclient client = new okhttpclient ();p Ublic 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) + ": " + responseheaders.value (i)); } system.out.println (Response.body (). String ());
The string () method of the response class loads all the contents of the document into memory for small documents that correspond to documents larger than 1M and should be obtained using a stream ().
Response.body (). ByteStream ()
Private final okhttpclient client = new okhttpclient ();p Ublic 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 e) { e.printstacktrace (); } @Override public void onresponse (response response) throws IOException { 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) + " : " + responseheaders.value (i)); } system.out.println (Response.body (). String ()); } });}
The read response blocks the current thread, so the originating request is in the main thread, and the callback's content is in the non-principal thread.
private static final mediatype media_type_markdown = mediatype.parse ("Text/x-markdown; charset=utf-8");p rivate final okhttpclient client = new okhttpclient ();p ublic void run () throws exception { String postBody = "" + "releases\n" + "--------\ n" + "\ n" + " * _1.0_ may 6, 2013\n " + " * _1.1_ june 15, 2013\n " + " * _1.2_ august 11, 2013\n "; request request = new Request.builder () .url ("https:// Api.github.com/markdown/raw ") .post ( Requestbody.create (media_type_markdown, postbody)) .build (); response response = client.newcall (Request). Execute (); if (!response.issuccessful ()) throw new ioexception ("unexpected code " + response); system.out.println (Response.body (). String ());
Because the entire request body is in memory, you should avoid submitting files above 1M.
Private final okhttpclient client = new okhttpclient ();p Ublic void run () throws Exception { RequestBody requestBody = new Requestbody () { @Override public mediatype contenttype () { 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 ("Unexpected code " + response"; system.out.println (Response.body (). String ());
Use the Okio framework to write content as a stream without a memory overflow problem.
public static final mediatype media_type_markdown = mediatype.parse ("Text/x-markdown; charset=utf-8");p rivate final okhttpclient client = new okhttpclient ();p ublic 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 ()) &nBsp; throw new ioexception ("unexpected code " + response); system.out.println (Response.body (). String ());
Private final okhttpclient client = new okhttpclient ();p Ublic void run () throws Exception { RequestBody formBody = new Formencodingbuilder () .add ("Search", "Jurassic park") .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 ()) &nBsp;throw new ioexception ("unexpected code " + response); system.out.println (Response.body (). String ());
Each names-values of the form is URL-encoded. If the server-side interface is not URL-encoded, a formbuilder can be customized.
private static final string imgur_client_id = "...";p rivate static Final mediatype media_type_png = mediatype.parse ("Image/png");p rivate final Okhttpclient client = new okhttpclient ();p ublic void run () throws exception { // use the imgur image upload api as documented at https://api.imgur.com/endpoints/image requestbody Requestbody = new multipartbuilder () .type (Multipartbuilder.form) .addpart ( headers.of ("Content-disposition", "form-data; name=\" title\ ""), &Nbsp; 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.imgur.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 ());}
This article is from the "My Way of Programming" blog, so be sure to keep this source http://aiwoapp.blog.51cto.com/8677066/1619401
One, Okhttp request method