Java Read Http Response Stream as Json

Fetch information dynamically

Contents
  • About JSON
  • Serializing data into JSON
  • Parsing JSON data
  • About URIs and HTTP requests
  • Using getString() to load a file
  • Using an HttpRequest object to load a file
    • Setting up the HttpRequest object
    • Sending the request
    • Handling the response
    • Populating the UI from JSON
  • Other resource

What'south the point?

  • Data on the web is oft formatted in JSON.
  • JSON is text based and human being readable.
  • The dart:catechumen library provides support for JSON.
  • Utilise HttpRequest to dynamically load data.

Web apps often employ JSON (JavaScript Object Note) to pass data between clients and servers. Information can be serialized into a JSON cord, which is and then passed between a client and server, and revived equally an object at its destination. This tutorial shows you lot how to use functions in the dart:convert library to produce and eat JSON data. Because JSON data is typically loaded dynamically, this tutorial too shows how a spider web app can use an HTTP request to get data from an HTTP server. For web apps, HTTP requests are served by the browser in which the app is running, and thus are subject area to the browser's security restrictions.

About JSON

The JSON data format is easy for humans to write and read because it is lightweight and text based. With JSON, diverse data types and elementary data structures such every bit lists and maps can be serialized and represented by strings.

Try it! The following app, its_all_about_you, displays the JSON string for data of various types. Click Run to start the app. Then change the values of the input elements, and check out the JSON format for each data type. Yous might adopt to open up the app in DartPad to take more infinite for the app'south lawmaking and UI.

The dart:convert library contains 2 user-friendly functions for working with JSON strings:

dart:convert part Description
json.decode() Builds Dart objects from a cord containing JSON information.
json.encode() Serializes a Dart object into a JSON string.

To utilize these functions, you need to import dart:convert into your Dart code:

The json.encode() and json.decode() functions can handle these Dart types automatically:

  • num
  • String
  • bool
  • Zip
  • List
  • Map

Serializing information into JSON

Use the json.encode() role to serialize an object that supports JSON. The _showJson() function, from the example, converts all of the data to JSON strings.

            void _showJson([Event? _]) {   // Grab the data that will be converted to JSON.   final favNum = int.tryParse(favoriteNumber.value ?? '');   terminal pi = double.tryParse(valueOfPi.value ?? '');   concluding chocolate = loveChocolate.checked;   final sign = horoscope.value;   concluding favoriteThings = <String>[     favOne.value ?? '',     favTwo.value ?? '',     favThree.value ?? '',   ];    final formData = {     'favoriteNumber': favNum,     'valueOfPi': pi,     'chocolate': chocolate,     'horoscope': sign,     'favoriteThings': favoriteThings   };    // Convert to JSON and display results.              intAsJson.text = json.encode(favNum);              doubleAsJson.text = json.encode(pi);              boolAsJson.text = json.encode(chocolate);              stringAsJson.text = json.encode(sign);              listAsJson.text = json.encode(favoriteThings);              mapAsJson.text = json.encode(formData);              }          

Shown below is the JSON string that results from the lawmaking using the original values from the app:

The JSON string for the its_all_about_you app

  • Numeric and boolean values appear equally they would if they were literal values in code, without quotes or other delineating marks.
  • A boolean value is either truthful or fake.
  • The null value is represented as nada.
  • Strings are contained within double quotes.
  • A list is delineated with square brackets; its items are comma-separated. The list in this example contains strings.
  • A map is delineated with curly brackets; it contains comma-separated cardinal/value pairs, where the central appears kickoff, followed by a colon, followed by the value. In this example, the keys in the map are strings. The values in the map vary in type but they are all JSON-parsable.

Parsing JSON data

Use the json.decode() role from the dart:convert library to create Dart objects from a JSON string. The case initially populates the values in the form from this JSON string:

const jsonDataAsString = '''{   "favoriteNumber": 73,   "valueOfPi": three.141592,   "chocolate": true,   "horoscope": "Cancer",   "favoriteThings": ["monkeys", "parrots", "lattes"] }''';  Map<Cord, dynamic> jsonData =     json.decode(jsonDataAsString) as Map<String, dynamic>;

This code calls json.decode() with a properly formatted JSON string.

In this example, the full JSON string is hard coded into the Dart lawmaking, only it could be created by the form itself or read from a static file or fetched from a server. An instance afterward in this folio shows how to dynamically fetch JSON data from a file that is co-located with the lawmaking for the app.

The json.decode() function reads the cord and builds Sprint objects from information technology. In this example, the json.decode() function creates a Map<Cord, dynamic> object based on the data in the JSON string. The Map contains objects of diverse types including an integer, a double, a boolean value, a regular string, and a list. All of the keys in the map are strings.

About URIs and HTTP requests

To make an HTTP GET request from within a web app, you lot need to provide a URI (Uniform Resource Identifier) for the resource. A URI is a graphic symbol cord that uniquely names a resource. A URL (Uniform Resource Locator) is a specific kind of URI that also provides the location of a resource. URLs for resources on the Globe Wide Web contain three pieces of information:

  • The protocol used for advice
  • The hostname of the server
  • The path to the resource

For example, the URL for this page breaks down as follows:

The tutorial URL

This URL specifies the HTTP protocol. When you enter an HTTP address into a spider web browser, the browser sends an HTTP Get request to a web server, and the web server sends an HTTP response that contains the contents of the folio (or an fault message).

Basic HTTP communication between client and server

Most HTTP requests in a web browser are simple GET requests request for the contents of a page. Still, the HTTP protocol allows for other types of requests, such as Mail for sending data from the client.

A Dart web app running inside of a browser can make HTTP requests. These HTTP requests are handled by the browser in which the app is running. Even though the browser itself tin can brand HTTP requests anywhere on the web, a Dart web app running inside the browser can brand only limited HTTP requests because of security restrictions. Practically speaking, because of these limitations, HTTP requests from spider web apps are primarily useful for retrieving information in files specific to and co-located with the app.

The SDK provides these useful classes for formulating URIs and making HTTP requests:

Dart lawmaking Library Clarification
Uri dart:core Uniform resource identifier
HttpRequest dart:html Customer-side HTTP asking object. For use in web apps.
HttpRequest dart:io Server-side HTTP request object. Does not work in web apps.

Using getString() to load a file

One useful HTTP request your spider web app can make is a Get request for a data file served from the aforementioned origin as the app. The example below reads a data file called portmanteaux.json that contains a JSON-formatted list of words. When you click the push, the app makes a GET request of the server and loads the file.

Try it! Click Run and then click the Get portmanteaux button.

This program uses a convenience method, getString(), provided by the HttpRequest grade to request the file from the server.

            Futurity<void> makeRequest(Event _) async {   const path = 'https://dart.dev/f/portmanteaux.json';   try {              // Make the Get request              final jsonString = await HttpRequest.getString(path);              // The asking succeeded. Procedure the JSON.              processResponse(jsonString);   } catch (e) {              // The GET request failed. Handle the mistake.              // ···   } }  void processResponse(String jsonString) {   for (final portmanteau in json.decode(jsonString)) {     wordList.children.add(LIElement()..text = portmanteau every bit Cord);   } }          

The getString() method uses a Hereafter object to handle the request. A Future is a manner to perform potentially time-consuming operations, such as HTTP requests, asynchronously. If you oasis't encountered futures yet, you tin can larn near them — as well as the async and await keywords — in the asynchronous programming codelab. Until then, y'all can employ the code higher up as a guide and provide your ain code for the body of the processResponse() office and your own code to handle the error.

Using an HttpRequest object to load a file

The getString() method is adept for an HTTP Become request that returns a string loaded from a resources. For other cases, yous demand to create an HttpRequest object, configure its header and other information, and utilise the send() method to make the request.

This section rewrites the portmanteaux code to explicitly construct an HttpRequest object.

Setting upwardly the HttpRequest object

The mouse-click handler for the button creates an HttpRequest object, configures it with a URI and callback role, and and then sends the request. Let'due south take a look at the Sprint code:

Future<void> makeRequest(Effect _) async {   const path = 'https://dart.dev/f/portmanteaux.json';   last httpRequest = HttpRequest();   httpRequest     ..open('GET', path)     ..onLoadEnd.listen((east) => requestComplete(httpRequest))     ..send(''); }

Making an HTTP GET request

Sending the request

The ship() method sends the request to the server.

Because the request in this example is a uncomplicated Go request, the code can send an empty string. For other types of requests, such as POST requests, this string can incorporate relevant data. You lot can also configure the HttpRequest object by setting various header parameters using the setRequestHeader() method.

Handling the response

To handle the HTTP response, you need to set upwards a callback part before calling send(). Our example sets upwardly a one-line callback function for onLoadEnd events that in turn calls requestComplete(). This callback function is chosen when the asking completes, either successfully or unsuccessfully.

Set up a callback function for request completion

The requestComplete() function checks the status code for the request.

            void requestComplete(HttpRequest request) {   if (request.status              == 200) {     final response =              asking.responseText;     if (response != null) {       processResponse(response);       return;     }   }    // The GET request failed. Handle the error.   // ··· }          

If the status code is 200, the file was found and loaded successfully. The content of the requested file (portmanteaux.json) is returned in the responseText property of an HttpRequest object.

Populating the UI from JSON

The data file in the portmanteaux case, portmanteaux.json, contains the post-obit JSON-formatted list of strings:

            [   "portmanteau", "fantabulous", "spork", "smog",   "spanglish", "gerrymander", "turducken", "stagflation",   "bromance", "freeware", "oxbridge", "palimony", "netiquette",   "brunch", "blog", "chortle", "Hassenpfeffer", "Schnitzelbank" ]          

Upon request, the server reads the file and sends it equally a unmarried cord to the client program.

Using json.decode(), the app easily converts the JSON-formatted list of words to a Dart listing of strings, creates a new LIElement for each one, and adds information technology to the <ul> chemical element on the page.

            void processResponse(Cord jsonString) {   for (final portmanteau in              json.decode(jsonString)) {     wordList.children.add(LIElement()..text = portmanteau as String);   } }          

Other resources

  • Using JSON
  • Asynchronous programming: futures, async, await

viningtherear.blogspot.com

Source: https://dart.dev/tutorials/web/fetch-data

0 Response to "Java Read Http Response Stream as Json"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel