目录

HTTP Data Request

When to Use

An application can initiate a data request over HTTP. Common HTTP methods include GET, POST, OPTIONS, HEAD, PUT, DELETE, TRACE, and CONNECT.

Before using this function, you need to configure a server domain name.

Available APIs

The HTTP data request function is mainly implemented by the HTTP module.

To use related APIs, you must request the ohos.permission.INTERNET permission.

For details, see Declaring Permissions.

The following table lists the involved APIs. For details, see @ohos.net.http (Data Request).

Name Description
createHttp() Creates an HTTP request.
request() Initiates an HTTP request to a given URL.
destroy() Destroys an HTTP request.
on(type: 'headersReceive') Registers an observer for HTTP Response Header events.
off(type: 'headersReceive') Unregisters the observer for HTTP Response Header events.

How to Develop

  1. Import the http namespace from @ohos.net.http.

  2. Call createHttp() to create an HttpRequest object.

  3. Call on() to subscribe to HTTP response header events. This API returns a response earlier than the request. It is up to you whether to listen for HTTP response header events.

  4. Call request() to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.

  5. Parse the returned result based on service requirements.

  6. Call off() to unsubscribe from HTTP response header events.

  7. Call destroy() to release resources after the request is processed.

// Import related modules.
import http from '@ohos.net.http';
import { BusinessError } from '@kit.BasicServicesKit';

// Each httpRequest corresponds to an HTTP request task and cannot be reused.
let httpRequest = http.createHttp();
// Subscribe to HTTP response headers. This callback is invoked before the request callback. Subscribe to this message as needed.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => {
  console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
  //Specify the URL for the HTTP request. The URL can include parameters or not. Specify request parameters in extraData.
  "EXAMPLE_URL",
  {
    method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
    // You can add header fields based on service requirements.
    header: {
      'Content-Type': 'application/json'
    },
    // This field is used to transfer the request body when a POST request is used. Its format needs to be negotiated with the server.
    extraData: "data to send",
    expectDataType: http.HttpDataType.STRING, // Optional. This parameter specifies the type of the return data.
    usingCache: true, // Optional. The default value is true.
    priority: 1, // Optional. The default value is 1.
    connectTimeout: 60000 // Optional. The default value is 60000, in ms.
    readTimeout: 60000, // Optional. The default value is 60000, in ms.
    usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
    usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API version 10.
  }, (err: BusinessError, data: http.HttpResponse) => {
    if (!err) {
      // data.result carries the HTTP response. Parse the response based on service requirements.
      console.info('Result:' + JSON.stringify(data.result));
      console.info('code:' + JSON.stringify(data.responseCode));
      // data.header carries the HTTP response header. Parse the content based on service requirements.
      console.info('header:' + JSON.stringify(data.header));
      console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
      // Call the destroy() method to release resources after HttpRequest is complete.
      httpRequest.destroy();
    } else {
      console.error('error:' + JSON.stringify(err));
      // Unsubscribe from HTTP Response Header events.
      httpRequest.off('headersReceive');
      // Call the destroy() method to release resources after HttpRequest is complete.
      httpRequest.destroy();
    }
  }
);