Application Octet Stream Java Example

OkHttp Get Request Java Example

In this post, we will create anOkHttp GET HTTP request example in Java.

OkHTTP is an open source project designed to be an efficient HTTP client for Android and Java applications.

OkHttp supports Android 5.0+ (API level 21+) and Java 1.8+. In this article, we will write a code using Java 1.8+.

OkHttp Get Request Examples

We will create the following different GET request examples:

  1. OkHttp GET Request Java Example
  2. Synchronous GET with OkHttp
  3. Asynchronous GET with OkHttp
  4. GET Request with Query Parameters
  5. Accessing Http Request Headers

Maven Dependency

Let's first add the library as a dependency into the pom.xml:

<dependency>     <groupId>com.squareup.okhttp3</groupId>     <artifactId>okhttp</artifactId>     <version>3.9.0</version> </dependency>

1. OkHttp GET Request Java Example

                  package                  com.javaguides.okhttp.tutorial.crud;                  import                  java.io.IOException;                  import                  okhttp3.OkHttpClient;                  import                  okhttp3.Request;                  import                  okhttp3.Response;                  public                  class                  OkHttpGet                  {                  OkHttpClient                  client                  =                  new                  OkHttpClient();                  public                  String                  run(String                  url)                  throws                  IOException                  {                  Request                  request                  =                  new                  Request.Builder().url(url).build();                  try                  (Response                  response                  =                  client.newCall(request).execute()) {                  return                  response.body().string();         }     }                  public                  static                  void                  main(String[]                  args)                  throws                  IOException                  {                  OkHttpGet                  example                  =                  new                  OkHttpGet();                  String                  response                  =                  example.run(                    "http://localhost:8080/api/v1/employees/1"                  );                  System                  .out.println(response);     } }

Below diagram shows the screenshot of source code as well as output:

2. Synchronous GET with OkHttp

To send synchronous GET request we need to build a Request object based on a URL and make a Call. After its execution we get back an instance of Response:

                  package                  com.javaguides.okhttp.tutorial;                  import                  java.io.IOException;                  import                  okhttp3.OkHttpClient;                  import                  okhttp3.Request;                  import                  okhttp3.Response;                  public                  class                  OkHttpGetExample                  {                  OkHttpClient                  client                  =                  new                  OkHttpClient();                  public                  String                  run(String                  url)                  throws                  IOException                  {                  Request                  request                  =                  new                  Request.Builder().url(url).build();                  try                  (Response                  response                  =                  client.newCall(request).execute()) {                  return                  response.body().string();         }     }                  public                  static                  void                  main(String[]                  args)                  throws                  IOException                  {                  OkHttpGetExample                  example                  =                  new                  OkHttpGetExample();                  String                  response                  =                  example.run(                    "https://raw.github.com/square/okhttp/master/README.md"                  );                  System                  .out.println(response);     } }

Output:

                OkHttp ======  An HTTP & HTTP/2 client for Android and Java applications. For more information see [the website][website] and [the wiki][wiki].  .....              

3. Asynchronous GET with OkHttp

Now, to make an asynchronous GET we need to enqueue a Call. A Callback allows us to read the response when it is readable. This happens after the response headers are ready.

Reading the response body may still block. OkHttp doesn't currently offer any asynchronous APIs to receive a response body in parts:

                  package                  com.javaguides.okhttp.tutorial;                  import                  java.io.IOException;                  import                  okhttp3.Call;                  import                  okhttp3.Callback;                  import                  okhttp3.OkHttpClient;                  import                  okhttp3.Request;                  import                  okhttp3.Response;                  public                  class                  OkHttpAsynchronousGetRequest                  {                  OkHttpClient                  client                  =                  new                  OkHttpClient();                  public                  static                  void                  main(String[]                  args)                  throws                  IOException                  {                  OkHttpAsynchronousGetRequest                  example                  =                  new                  OkHttpAsynchronousGetRequest();         example.run(                    "https://raw.github.com/square/okhttp/master/README.md"                  );     }                  public                  void                  run(String                  url)                  throws                  IOException                  {                  Request                  request                  =                  new                  Request.Builder().url(url).build();                  Call                  call                  =                  client.newCall(request);         call.enqueue(new                  Callback() {                  public                  void                  onResponse(Call                  call,                  Response                  response)                  throws                  IOException                  {                  System                  .out.println(                    "on Success"                  );                  System                  .out.println(response.toString());             }                  public                  void                  onFailure(Call                  call,                  IOException                  e) {                  System                  .out.println(                    "onFailure"                  );             }         });     } }

Output:

                on Success Response{protocol=http/1.1, code=200, message=OK, url=https://raw.githubusercontent.com/square/okhttp/master/README.md}              

4. GET Request with Query Parameters

Finally, to add query parameters to our GET request we can take advantage of the HttpUrl.Builder.

After the URL is built we can pass it to our Request object:

                  package                  com.javaguides.okhttp.tutorial;                  import                  java.io.IOException;                  import                  okhttp3.HttpUrl;                  import                  okhttp3.OkHttpClient;                  import                  okhttp3.Request;                  import                  okhttp3.Response;                  public                  class                  OkHttpGetQueryParametersExample                  {                                      //                    avoid creating several instances, should be singleon                  OkHttpClient                  client                  =                  new                  OkHttpClient();                  public                  static                  void                  main(String[]                  args)                  throws                  IOException                  {                  OkHttpGetQueryParametersExample                  example                  =                  new                  OkHttpGetQueryParametersExample();                  HttpUrl                  .                  Builder                  urlBuilder                  =                  HttpUrl                  .parse(                    "https://api.github.com"                  ).newBuilder();         urlBuilder.addQueryParameter(                    "v"                  ,                                      "3.0"                  );         urlBuilder.addQueryParameter(                    "user"                  ,                                      "RameshMF"                  );                  String                  url                  =                  urlBuilder.build().toString();                  System                  .out.println(                    "Print URL :                    "                                    +                  url);                  System                  .out.println(example.run(url));     }                                      //                    Common method to execute and return response                  public                  String                  run(String                  url)                  throws                  IOException                  {                  Request                  request                  =                  new                  Request.Builder().url(url).build();                  try                  (Response                  response                  =                  client.newCall(request).execute()) {                  return                  response.body().string();         }     } }

Output:

                Print URL : https://api.github.com/?v=3.0&user=RameshMF {"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url": ....              

5. Accessing Http Request Headers

                  package                  com.javaguides.okhttp.tutorial;                  import                  java.io.IOException;                  import                  okhttp3.OkHttpClient;                  import                  okhttp3.Request;                  import                  okhttp3.Response;                  public                  class                  OkHttpHeadersExample                  {                  private                  final                  OkHttpClient                  client                  =                  new                  OkHttpClient();                  public                  static                  void                  main(String[]                  args)                  throws                  Exception                  {                  OkHttpHeadersExample                  example                  =                  new                  OkHttpHeadersExample();         example.run();     }                  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();                  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"                  ));         }     } }

Output:

                Server: GitHub.com Date: Mon, 27 May 2019 06:59:49 GMT Vary: [Accept]              

Related Posts

  • OkHttp GET, POST, PUT and DELETE Request Java Examples
  • OkHttp Get Request Java Example
  • OkHttp POST Request Java Example
  • OkHttp PUT Request Java Example

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

earleyrepliseen.blogspot.com

Source: https://www.javaguides.net/2019/05/okhttp-get-request-java-example.html

0 Response to "Application Octet Stream Java Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel