React Native Networking API

Source: Internet
Author: User

Networking (Network)

Most mobile applications need to load data resources from a remote URL, so we need to send a request to an interface, or just get a static content from another server .

1.Using Fetch (using Fetch)

React Native provides us with the fetch API required for network requests.

Making Requests (initiating a request )

Want to get content from any URL? You only need to get through the URL :

Fetch (' Https://mywebsite.com/mydata.json ')

Fetch Optional parameters that allow you to customize the HTTP request, you can specify headers or use post/get to make the request :

Fetch (' https://mywebsite.com/endpoint/', {  method:' POST ',  headers:{      ' Accept ': ' Application/json ',      ' content-type ': ' Application/json ',  },  body: Json.stringify ({      firstparam:' Yourvalue ',      secondparam:' Yourothervalue ',  }) })

2.Handling The response (processing response)

In the example above we have learned how to initiate a request, and after the request is initiated, we can usually get the response to the request .

The network request here is an asynchronous operation that will return a response Promise (Commit/state), and here is an example code for the asynchronous request :

function Getmoviesfromapiasync () {  return fetch (' https://facebook.github.io/react-native/ Movies.json ')      . Then ((response)=Response.json ())      . Then ((responsejson)+ ={         return responsejson.movies;      })      . Catch (Error) ={        console.error (error);      });

You can use the ES2017 async/await syntax to write :

function Getmoviesfromapi () {      try  {        = await fetch (' https://facebook.github.io/ React-native/movies.json ');         = await Response.json ();         return responsejson.movies;       Catch (Error) {        console.error (error);      }}

Do not forget to catch the error, if not captured, the system will be automatically discarded .

By default, IOS will block any requests that do not use SSL encryption, and if you need to use an unencrypted URL , you need to add a transport security exception .
If you know the domain that the URL is accessing, then adding an exception will be more complete. You can prohibit ATS.

3.Using other Networking Libraries (using a different network library)

The React native has a built-in XMLHttpRequest API. This allows you to use a third-party library, such as Frisbee or Axios, or you can request it directly using the XMLHttpRequest API.

var New  = (e) + =      {if (request.readystate!== 4)        {return;      }        if (Request.status = = =) {        console.log (' success ', request. responsetext)      ; Else {        Console.warn (' error ');}      }; Request.open (' GET ', ' https://mywebsite.com/endpoint/'); Request.send ();

XMLHttpRequest's security model is different from the Web, because native apps don't have the concept of cors.

4.WebSocket Support (WebSocket)

The React native supports WebSockets, a protocol that provides a two-way communication channel in a single TCP connection.

varWS =NewWebSocket (' Ws://host.com/path '); Ws.onopen= () + = {    //Connection opened connection openWs.send (' something ');//send a message message};ws.onmessage= (e) = = {    //a message was received received a messageConsole.log (e.data);}; Ws.onerror= (e) = = {    //An error occurred has occurredConsole.log (e.message);}; Ws.onclose= (e) = = {    //Connection closed connection offConsole.log (E.code, E.reason);};

React Native Networking API

Related Article

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.