A heartbreaking experience using OKHTTP

Recently because of some necessity, exposed to the OKHttp, the pain is also pretty Dan, before colleagues will produce attachment upload address configuration into test, also good small, did not cause too big effect, moreover is the colleagues and quit, then can only silently in the heart of a greeting he N times, of course, after the greetings, Data synchronization had to continue. 😭

OKHTTP official address: OKHTTP

A heartbreaking experience using OKHTTP


introduce

As the introduction on OkHttp’s official website is very detailed, I can only paste a translated passage of introduce:

HTTP is a form of modern application networking. This is how we exchange data and media. Using HTTP efficiently can make your things load faster and save bandwidth.

OkHttp is an efficient Http client that by default:

  • HTTP / 2 support allows all requests from the same host to share a socket.
  • Connection pooling reduces request latency (if HTTP / 2 is not available).
  • Transparent GZIP reduces the download size.
  • Response caching can completely avoid repeated network requests.

But in my case, OkHttp is much easier to use than Apache-HTTP and has a more intuitive hierarchy.


Usage scenarios

In this scenario, files uploaded to the test environment are downloaded to the local PC and then uploaded to the production environment.

The solution process is as follows:

  • Paste the error data from the database table into a new Excel file created locally. (Connecting directly to the database is riskier, after all)

  • Read the information in Excel to get the file address.

  • Request file address, get stream file information.

  • Take the stream file information, assemble the uploaded data, and upload it to the new production environment.

  • After the upload is complete, the production environment file address is obtained.

  • The updated SQL statement is generated when the production file address is obtained.

  • To execute SQL statements in the database.


Use process

The SRC /test/ Java directory is used to create a Java class.

Introducing OKHttp dependencies:

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.3.1</version>
</dependency>
Copy the code

With the introduction of the OKHTTP JAR, you’re basically free to make your own crazy Http requests.

For example, it directly synchronizes and asynchronizes requests:

Synchronous GET

  private final OkHttpClient client = new OkHttpClient();

  public void run(a) throws Exception {
    Request request = new Request.Builder()
        .url("https://publicobject.com/helloworld.txt")
        .build();

    try (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()); }}Copy the code

Asynchronous GET

 private final OkHttpClient client = new OkHttpClient();

  public void run(a) throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();

    client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
        e.printStackTrace();
      }

      @Override public void onResponse(Call call, Response response) throws IOException {
        try (ResponseBody responseBody = response.body()) {
          if(! response.isSuccessful())throw new IOException("Unexpected code " + response);

          Headers responseHeaders = response.headers();
          for (int i = 0, size = responseHeaders.size(); i < size; i++) {
            System.out.println(responseHeaders.name(i) + ":"+ responseHeaders.value(i)); } System.out.println(responseBody.string()); }}}); }Copy the code

The Header information

private final OkHttpClient client = new OkHttpClient();

  public void run(a) 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();

    try (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")); }}Copy the code

POST requests flow information

public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("text/x-markdown; charset=utf-8");

  private final OkHttpClient client = new OkHttpClient();

  public void run(a) throws Exception {
    RequestBody requestBody = new RequestBody() {
      @Override public MediaType contentType(a) {
        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;
        }
        returnInteger.toString(n); }}; Request request =new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(requestBody)
        .build();

    try (Response response = client.newCall(request).execute()) {
      if(! response.isSuccessful())throw new IOException("Unexpected code "+ response); System.out.println(response.body().string()); }}Copy the code

POST Requests File information

  public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("text/x-markdown; charset=utf-8");

  private final OkHttpClient client = new OkHttpClient();

  public void run(a) 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();

    try (Response response = client.newCall(request).execute()) {
      if(! response.isSuccessful())throw new IOException("Unexpected code "+ response); System.out.println(response.body().string()); }}Copy the code

Post form submission

 private final OkHttpClient client = new OkHttpClient();

  public void run(a) throws Exception {
    RequestBody formBody = new FormBody.Builder()
        .add("search"."Jurassic Park")
        .build();
    Request request = new Request.Builder()
        .url("https://en.wikipedia.org/w/index.php")
        .post(formBody)
        .build();

    try (Response response = client.newCall(request).execute()) {
      if(! response.isSuccessful())throw new IOException("Unexpected code "+ response); System.out.println(response.body().string()); }}Copy the code

POST multiple Body requests

  /** * The imgur client ID for OkHttp recipes. If you're using imgur for anything other than running * these examples, please request your own client ID! https://api.imgur.com/oauth2 */
  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(a) throws Exception {
    // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
    RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("title"."Square Logo")
        .addFormDataPart("image"."logo-square.png",
            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();

    try (Response response = client.newCall(request).execute()) {
      if(! response.isSuccessful())throw new IOException("Unexpected code "+ response); System.out.println(response.body().string()); }}Copy the code

Because most of the use process is based on the official website examples, so the code used this time is similar to the official examples, of course, it is not too shy to post, haha. 😁


conclusion

OkHttp is a bit of a beginner’s game. When I wrote apache-HTTP over and over again, I felt that APche was a bit redundant. I wanted to have a lightweight, easy to use, easy to understand HTTP-client. 😂

More examples of these requests can be found at okhttp-request-example

References:

OkHttp.io

OKhttp-Request-example

OKHttp-Github