Learning from Android Network Framework OKHttp and androidokhttp

Source: Internet
Author: User

Learning from Android Network Framework OKHttp and androidokhttp
OKHTTPokHttp: OKHttp is an Http client for Android. Very efficient. Supports SPDY, connection pool, GZIP, and HTTP cache. By default, OKHttp automatically handles common network problems, such as secondary connections and SSL handshakes. If your application integrates OKHttp, ingress fit uses OKHttp by default to process requests from other network layers.
An HTTP & SPDY client for Android and Java applicationsFrom Android4.4, the underlying implementation of HttpURLConnection uses okHttp.
Usage requirements: for Android: 2.3 and later, for Java: java7 and later modules: okhttp-urlconnection implementation. HttpURLConnection API; okhttp-apache implementation Apache HttpClient API. Dependency:Okio(Https://github.com/square/okio): Okio, which OkHttp uses for fast I/O and resizable buffers. Installation: maven:

<dependency>  <groupId>com.squareup.okhttp</groupId>  <artifactId>okhttp</artifactId>  <version>2.3.0</version></dependency>
Gradle:
compile 'com.squareup.okhttp:okhttp:2.3.0'
Get a url synchronization GET:
  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) + ": " + responseHeaders.value(i));    }    System.out.println(response.body().string());  }
Asynchronous GET: downloads files in a work thread and calls back the Callback interface when the response is readable. The current thread is blocked when the response is read. OkHttp currently does not provide asynchronous APIs to receive response bodies.
  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, Throwable throwable) {        throwable.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());      }    });  }
Access Header:
  private final OkHttpClient client = new OkHttpClient();  public void run() throws Exception {    Request request = new Request.Builder()        .url("https://api.github.com/repos/square/okhttp/issues")        .header("User-Agent", "OkHttp Headers.java")        .addHeader("Accept", "application/json; q=0.5")        .addHeader("Accept", "application/vnd.github.v3+json")        .build();    Response response = client.newCall(request).execute();    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);    System.out.println("Server: " + response.header("Server"));    System.out.println("Date: " + response.header("Date"));    System.out.println("Vary: " + response.headers("Vary"));  }
Post to a SERVERPosting a String:
public static final MediaType jsonReq    = MediaType.parse("application/json; charset=utf-8");OkHttpClient client = new OkHttpClient();String post(String url, String json) throws IOException {  RequestBody body = RequestBody.create(jsonReq, json);  Request request = new Request.Builder()      .url(url)      .post(body)      .build();  Response response = client.newCall(request).execute();  return response.body().string();}
Posting Streaming:
 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 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) + " × " + 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());  }
Posting a File:
 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());  }
Posting from parameters:
private final OkHttpClient client = new OkHttpClient();  public 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()) throw new IOException("Unexpected code " + response);    System.out.println(response.body().string());  }
Posting a multipart request:
 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/image    RequestBody requestBody = new MultipartBuilder()        .type(MultipartBuilder.FORM)        .addPart(            Headers.of("Content-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.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());  }
Posing Json with Gson
 private final OkHttpClient client = new OkHttpClient();  private final Gson gson = new Gson();  public void run() throws Exception {    Request request = new Request.Builder()        .url("https://api.github.com/gists/c2a7c39532239ff261be")        .build();    Response response = client.newCall(request).execute();    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);    Gist gist = gson.fromJson(response.body().charStream(), Gist.class);    for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {      System.out.println(entry.getKey());      System.out.println(entry.getValue().content);    }  }  static class Gist {    Map<String, GistFile> files;  }  static class GistFile {    String content;  }
Response Caching: In order to cache the Response, you need a cache directory that you can read and write, and the cache size limit. This cache directory should be private, and untrusted programs should not be able to read the cached content.
It is incorrect that a cache directory has multiple cache accesses at the same time. Most programs only need to call new OkHttp () once, configure the Cache during the first call, and then you only need to call this instance elsewhere. Otherwise, the two cache examples interfere with each other, damage the response cache, and may cause program crash.
The response cache uses the HTTP header as the configuration. You can add Cache-Control: max-stale = 3600 to the Request Header, which is supported by the OkHttp Cache. Your Service determines the response Cache duration through the response header, for example, using Cache-Control: max-age = 9600.
private final OkHttpClient client;  public CacheResponse(File cacheDirectory) throws Exception {    int cacheSize = 10 * 1024 * 1024; // 10 MiB    Cache cache = new Cache(cacheDirectory, cacheSize);    client = new OkHttpClient();    client.setCache(cache);  }  public void run() throws Exception {    Request request = new Request.Builder()        .url("http://publicobject.com/helloworld.txt")        .build();    Response response1 = client.newCall(request).execute();    if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1);    String response1Body = response1.body().string();    System.out.println("Response 1 response:          " + response1);    System.out.println("Response 1 cache response:    " + response1.cacheResponse());    System.out.println("Response 1 network response:  " + response1.networkResponse());  }
Canceling a Call
    final Call call = client.newCall(request);        call.cancel();
Timeouts:
private final OkHttpClient client;  public ConfigureTimeouts() throws Exception {    client = new OkHttpClient();    client.setConnectTimeout(10, TimeUnit.SECONDS);    client.setWriteTimeout(10, TimeUnit.SECONDS);    client.setReadTimeout(30, TimeUnit.SECONDS);  }
Handling Authentication:
private final OkHttpClient client = new OkHttpClient();  public void run() throws Exception {    client.setAuthenticator(new Authenticator() {      @Override public Request authenticate(Proxy proxy, Response response) {        System.out.println("Authenticating for response: " + response);        System.out.println("Challenges: " + response.challenges());        String credential = Credentials.basic("jesse", "password1");        return response.request().newBuilder()            .header("Authorization", credential)            .build();      }      @Override public Request authenticateProxy(Proxy proxy, Response response) {        return null; // Null indicates no attempt to authenticate.      }    });    Request request = new Request.Builder()        .url("http://publicobject.com/secrets/hellosecret.txt")        .build();    Response response = client.newCall(request).execute();    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);    System.out.println(response.body().string());  }
To avoid multiple retries when the verification fails, we can discard the verification by returning null:
If (responseCount (response)> = 3) {return null; // If we 've failed 3 times, give up .} // Add the following method private int responseCount (Response response) {int result = 1; while (response = response. priorResponse ())! = Null) {result ++;} return result ;}
Interceptors
class LoggingInterceptor implements Interceptor {  @Override public Response intercept(Chain chain) throws IOException {    Request request = chain.request();    long t1 = System.nanoTime();    logger.info(String.format("Sending request %s on %s%n%s",        request.url(), chain.connection(), request.headers()));    Response response = chain.proceed(request);    long t2 = System.nanoTime();    logger.info(String.format("Received response for %s in %.1fms%n%s",        response.request().url(), (t2 - t1) / 1e6d, response.headers()));    return response;  }}

Application Interceptors:
OkHttpClient client = new OkHttpClient();client.interceptors().add(new LoggingInterceptor());
Network Interceptors
OkHttpClient client = new OkHttpClient();client.networkInterceptors().add(new LoggingInterceptor());

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.