Read Json From a Url in Gson

In this tutorial, nosotros'll acquire about the HttpClient library introduced in Coffee 11 for sending HTTP requests. We'll too run into how to utilize the Gson library from Google to parse JSON data.

We'll be using a single source file for our app which can exist executed in Coffee xi using the java command without first compiling it (using javac)merely like a script file.

Sending Http Requests Prior to Java 11

Prior to Java eleven, developers had to utilise URLConnection to send HTTP requests. This package doesn't take an like shooting fish in a barrel to use API and doesn't support the newer HTTP/2 protocol - As a result developers resorted to use third-political party libraries similar Apache HTTP Customer

Notation: HttpClient doesn't currently have some advanced features like multi-function form information and compression support.

Prerequisites

Yous will need to take Java 11 LTS version installed on your system. You tin can just go to the official website and download the appropriate installer for your operating system. If you are using Ubuntu xix.04, yous can also follow this tutorial to install Java xi on your system.

You will besides need some working knowledge of Coffee.

How to Apply HttpClient in Coffee 11?

HttpClient is available from the java.net.http packet.

Using HttpClient is equally like shooting fish in a barrel as adding one line of lawmaking:

                          client              =              HttpClient              .              newHttpClient              ();                      

Or besides:

                          client              =              HttpClient              .              newBuilder              ().              build              ();                      

You lot can also customize every aspect of the client:

                          var              client              =              HttpClient              .              newBuilder              ()              .              authenticator              (              Authenticator              .              getDefault              ())              .              connectTimeout              (              Duration              .              ofSeconds              (              60              ))              .              cookieHandler              (              CookieHandler              .              getDefault              ())              .              executor              (              Executors              .              newFixedThreadPool              (              3              ))              .              followRedirects              (              Redirect              .              NEVER              )              .              priority              (              2              )              .              proxy              (              ProxySelector              .              getDefault              ())              .              sslContext              (              SSLContext              .              getDefault              ())              .              version              (              Version              .              HTTP_2              )              .              sslParameters              (              new              SSLParameters              ())              .              build              ();                      

These methods are used to change the default values of settings like:

  • HTTP/2,
  • Connection timeout,
  • Redirection policy,
  • Cookie handlers,
  • Authentication,
  • The proxy selector,
  • SSL.

You tin can also use HttpRequest bachelor from the java.cyberspace.HttpRequest bundle to create requests and HttpResponse available from the java.net.HttpResponse package to piece of work with response objects. For example:

                          var              httpRequest              =              HttpRequest              .              newBuilder              ()              .              uri              (              URI              .              create              (              "https://www.techiediaries/feed.xml"              ))              .              GET              ()              .              build              ();                      

Here, we specify the request URI using the uri() method , we call the GET() method to specify a Get request and and we call build() to create an example of HttpRequest. Y'all can also use the other methods such as GET(), POST(), DELETE() and PUT() or y'all can use method() to specify any HTTP method:

                          var              asking              =              HttpRequest              .              newBuilder              (              URI              .              create              (              "https://www.techiediaries/feed.xml"              ))              .              method              (              "Head"              ,              BodyPublishers              .              noBody              ())              .              build              ();                      

You can use BodyPublishers.noBody() for requests that don't wait a body.

After building your request, you lot can send it using the transport() method of the client:

                          HttpResponse              <              String              >              response              =              client              .              send              (              request              ,              BodyHandlers              .              ofString              ());                      

BodyHandlers.ofString() converts the response raw data to a Cord. These are other options:

                          BodyHandlers:              :              ofByteArray              BodyHandlers:              :              ofFile              BodyHandlers:              :              ofString              BodyHandlers:              :              ofInputStream                      

Note: You lot can also send requests asynchronously using the sendAsync() method. Check the docs for more data.

Coffee 11 & HttpClient Example

Now, let's build a simple Java 11 instance application that makes apply of HttpClient to fetch information from a tertiary-party Rest API and display it. We'll be using a news REST API available from newsapi.

You commencement need to head to their website and register for an API fundamental.

Afterward submitting the course. You will be redirected to a folio where yous can get your API central.

Java 11 Single Source Files or Scripts

Starting with Java 11, you tin can write script files as you don't take to first compile your source code with javac before executing it with coffee.

For a single source code file, you can run the file directly with the java control and JVM volition execute it. You lot can even employ the shebang syntax in Unix based systems like Linux and macOS.

Open up a new concluding, navigate inside a working folder and create a single file with the .java extension:

Next, open the file and add the post-obit code:

                          public              grade              NewsScript              {              public              static              void              main              (              String              []              args              )              {              Organization              .              out              .              println              (              "### NewsScript! v1.0: Get Daily News ###"              );              }              }                      

We simply create a Java grade with a static master method and we phone call the println() method to display the ### NewsScript! v1.0: Get Daily News ### string on the console.

Allow's now run the file. Head back to your terminal and run the following command:

If y'all have Java 11, that should run the file and brandish the message on the console.

Sending HTTP Become Requests with Java 11+ HttpClient

Now, let's actually get the news. In your source file add the following lawmaking:

                          import              java.internet.http.HttpClient              ;              import              java.net.http.HttpRequest              ;              import              java.net.http.HttpResponse              ;              import              java.internet.URI              ;              public              class              NewsScript              {              public              static              void              main              (              String              []              args              )              {              System              .              out              .              println              (              "### NewsScript! v1.0: Get Daily News ###"              );              String              API_KEY              =              "<YOUR_API_KEY_HERE>"              ;              var              client              =              HttpClient              .              newHttpClient              ();              var              httpRequest              =              HttpRequest              .              newBuilder              ()              .              uri              (              URI              .              create              (              String              .              format              (              "https://newsapi.org/v2/tiptop-headlines?sources=techcrunch&apiKey=%south"              ,              API_KEY              )))              .              GET              ()              .              build              ();              endeavour              {              var              response              =              customer              .              send              (              httpRequest              ,              HttpResponse              .              BodyHandlers              .              ofString              ());              System              .              out              .              println              (              response              .              body              ());              }              take hold of              (              Exception              e              ){              e              .              printStackTrace              ();              }              }              }                      

Brand sure your replace <YOUR_API_KEY_HERE> with your actual API primal from the News API.

If your run this code, you should get the news data printed as a JSON string with news entries.

Parsing JSON Data with Gson in Java 11

We need to parse the JSON string as a Java object and then we can piece of work with it.

Since Java doesn't have whatsoever native JSON module, we'll make employ of gson, a library by Google for working with JSON in Java.

Since we are creating a single file script without Maven or Gradle, we need to download the jar file of the library and put it in the folder of our Java file.

Head to this Maven repo and download the .jar file.

Now, when running the script, you should add the current folder in the class path of your app every bit follows:

                          $              java --class-path              './*'              NewsScript.java                      

Adjacent, let's parse our news data into Java objects. First, we need to create the following Data Transfer Objects or DTOs that correspond to the JSON construction of the returned data:

                          class              NewsDTO              {              String              status              ;              int              totalResults              ;              ArrayList              <              ArticleDTO              >              articles              ;              }              class              ArticleDTO              {              SourceDTO              source              ;              Cord              author              ;              String              title              ;              String              description              ;              String              url              ;              }              class              SourceDTO              {              String              id              ;              String              name              ;              }                      

You need to import ArrayList using import java.util.ArrayList; in your code.

Note: These DTOs should be placed below the main class.

Adjacent, import the Gson class:

                          import              com.google.gson.Gson              ;                      

Next, change the code in the effort{} catch(){} block inside the main() method as follows:

                          try              {              var              response              =              client              .              send              (              httpRequest              ,              HttpResponse              .              BodyHandlers              .              ofString              ());              NewsDTO              obj              =              new              Gson              ().              fromJson              (              response              .              body              (),              NewsDTO              .              grade              );              for              (              ArticleDTO              art              :              obj              .              articles              )              {              System              .              out              .              println              (              "### "              +              art              .              title              +              " ### \n"              );              Organization              .              out              .              println              (              art              .              description              );              System              .              out              .              println              (              "\nRead more than: "              +              art              .              url              +              "\due north"              );              }              }              catch              (              Exception              e              ){              e              .              printStackTrace              ();              }                      

We simply phone call the fromJson() method bachelor from the Gson instance and we pass in the response body which contains a JSON string. This volition convert the string to an object of the NewsDTO type.

Finally, we iterate over the articles array (of ArticleDTO objects) from the NewsDTO object and we impress the championship, description and URL of each item to the standard output.

That'due south it! If we run our script using the following command:

                          $              java --form-path              './*'              NewsScript.java                      

We should get something like the following screenshot:

Java 11 HttpClient Example

Enjoy your daily news from your terminal. Y'all tin click on each particular's URL to read the full article on your web browser.

This is the full code source of the Java 11 script:

                          import              java.util.ArrayList              ;              import              java.internet.http.HttpClient              ;              import              java.net.http.HttpRequest              ;              import              java.net.http.HttpResponse              ;              import              coffee.cyberspace.URI              ;              import              com.google.gson.Gson              ;              public              class              NewsScript              {              public              static              void              chief              (              String              []              args              )              {              Organisation              .              out              .              println              (              "### NewsScript! v1.0: Become Daily News ###"              );              String              API_KEY              =              "<YOUR_API_KEY_HERE>"              ;              var              client              =              HttpClient              .              newHttpClient              ();              var              httpRequest              =              HttpRequest              .              newBuilder              ()              .              uri              (              URI              .              create              (              String              .              format              (              "https://newsapi.org/v2/height-headlines?sources=techcrunch&apiKey=%s"              ,              API_KEY              )))              .              Go              ()              .              build              ();              endeavor              {              var              response              =              client              .              ship              (              httpRequest              ,              HttpResponse              .              BodyHandlers              .              ofString              ());              //System.out.println(response.body());              NewsDTO              obj              =              new              Gson              ().              fromJson              (              response              .              body              (),              NewsDTO              .              grade              );              //Organisation.out.println(obj.articles);              for              (              ArticleDTO              art              :              obj              .              articles              )              {              Organisation              .              out              .              println              (              "### "              +              art              .              title              +              " ### \n"              );              Arrangement              .              out              .              println              (              art              .              description              );              System              .              out              .              println              (              "\nRead more: "              +              fine art              .              url              +              "\n"              );              }              }              take hold of              (              Exception              e              ){              e              .              printStackTrace              ();              }              }              }              class              NewsDTO              {              String              status              ;              int              totalResults              ;              ArrayList              <              ArticleDTO              >              articles              ;              }              grade              ArticleDTO              {              SourceDTO              source              ;              Cord              author              ;              Cord              title              ;              String              description              ;              String              url              ;              }              class              SourceDTO              {              String              id              ;              String              name              ;              }                      

Conclusion

In this tutorial, nosotros've used Coffee xi HttpClient for sending HTTP requests with the Gson library for parsing JSON data to build a simple news application that allows you to read news from your last.


Read Json From a Url in Gson

Source: https://www.techiediaries.com/java/java-11-httpclient-gson-send-http-get-parse-json-example/

0 Response to "Read Json From a Url in Gson"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel