urlopen 模块

urlopen 模块提供 API 以通过 HTTP, HTTPS, Kafka或 IBM® MQ 协议与目标服务器建立非流式连接,并在 DataPower® 文件系统中打开文件。 API 还可以在 GatewayScript 操作中发送和接收 IBM MQ 消息。

要访问 urlopen 模块中的 API ,请使用 require('urlopen') 语句,例如 var urlopen = require('urlopen');

urlopen 模块提供 urlopen.open() API 以执行以下行为。
  • 如果要使用用户代理程序对本地服务发起请求以动态建立与目标服务器的连接,请创建用户代理程序对象并在 urlopen.open() API 中使用该对象。
    UserAgent 对象
    urlopen.open() API 通过 HTTP, HTTPS或 IBM MQ 协议与目标服务器建立连接时,将使用用户代理程序对象。 假定 UserAgent 对象表示用户代理程序对象。
    HttpUser代理程序对象
    urlopen.open() API 通过 HTTP 或 HTTPS 协议与目标服务器建立连接时,将使用特定于 HTTP的用户代理程序对象。 假定 HttpUserAgent 对象表示特定于 HTTP的用户代理程序对象。
  • 通过 HTTP, HTTPS或 IBM MQ 协议与目标服务器建立连接。
  • 建立连接后,来自目标服务器的响应由 urlopen.open() API 的 callback 参数处理。
    urlopen.open() 错误响应
    发生错误时, urlopen.open() API 可以接收错误代码,这些错误代码提供了帮助您从错误中恢复的信息。
    响应对象
    您可以使用 response 对象支持的读 API 来获取数据。 假定 response 对象由 urlopen.open() API 初始化。 读 API 包括 response.readAsBuffer()response.readAsBuffers()response.readAsXML()response.readAsJSON()
  • urlopen.open() 以在 DataPower Gateway上打开文件

UserAgent 对象

如果要使用用户代理程序对本地服务发起请求以动态建立与目标服务器的连接,请创建 UserAgent 对象并在 urlopen.open() API 中调用该对象。

当包含 urlopen.open() API 的 GatewayScript 文件由 GatewayScript 操作调用时, GatewayScript 用户代理属性将覆盖在用户代理中为 XML 管理器或变量配置的特定属性。 特定属性具有与 UserAgent 对象的属性相同的功能。

用于创建 UserAgent 对象的类构造函数: urlopen.UserAgent 类构造函数

用于管理 UserAgent 对象的 API: UserAgent API


urlopen.UserAgent 类构造函数

使用 urlopen.UserAgent() 类构造函数来创建 UserAgent 对象。

new urlopen.UserAgent()

创建并初始化 UserAgent 对象。 当 urlopen.open() API 通过 HTTP, HTTPS或 IBM MQ 协议与目标服务器建立连接时,将使用 UserAgent 对象。

语法

new urlopen.UserAgent([ua_options])
ua_optionsJSON 对象。
示例
创建并初始化 UserAgent 对象。
var urlopen = require(’urlopen’);
var UserAgent = new urlopen.UserAgent({persistentConnection: false});

UserAgent API

UserAgent 对象提供以下 API 来管理用户代理程序。

所有 API 规范都使用假定由 urlopen.UserAgent() 类构造函数定义的 UserAgent 对象。
用于管理 UserAgent 对象的 API。

UserAgent.prototype.get()

返回 UserAgent 对象的特定属性值或返回 UserAgent 对象。

语法

UserAgent.prototype.get([name])
名称UserAgent 对象中的属性名。 有效属性名为 persistenConnection
指定属性名称时,将返回属性值。 否则,将返回 UserAgent 对象。 指定无效属性名时,将返回 undefined

UserAgent.prototype.set()

配置 UserAgent 对象的特定属性。

语法

UserAgent.prototype.set(名称)
UserAgent.prototype.set({name: value})
名称UserAgent 对象中的属性名。 有效属性在 urlopen.UserAgent() API 的 ua_options 参数中定义。
要分配给属性的值。

HttpUserAgent 对象

如果要使用特定于 HTTP的 HttpUserAgent 用户代理程序来启动本地服务请求以动态建立与目标服务器的连接,请创建 HttpUserAgent 对象并在 urlopen.open() API 中调用该对象。

当包含 urlopen.open() API 的 GatewayScript 文件由 GatewayScript 操作调用时, GatewayScript 用户代理属性将覆盖在用户代理中为 XML 管理器或变量配置的特定属性。 特定属性具有与 HttpUserAgent 对象的属性相同的功能。

用于创建 HttpUserAgent 对象的类构造函数: urlopen.HttpUserAgent 类构造函数

用于管理 HttpUserAgent 对象的 API: HttpUser代理程序 API


urlopen.HttpUserAgent 类构造函数

urlopen.HttpUserAgent 类派生自 urlopen.UserAgent 类。 使用 urlopen.HttpUserAgent() 类构造函数来创建和初始化 HttpUserAgent 用户代理程序对象。

new urlopen.HttpUserAgent()

创建并初始化 HttpUserAgent 用户代理程序对象。 当 urlopen.open() API 通过 HTTP 或 HTTPS 协议与目标服务器建立连接时,将使用 HttpUserAgent 对象。

语法

新的 urlopen.HttpUserAgent([ua_options])
ua_options由特定于 HTTP 或 HTTPS 协议的属性组成的 JSON 对象。
示例
创建并初始化 HttpUserAgent 对象。
var urlopen = require(’urlopen’);
// define the http-specific user agent properties
var ua_options = {    
    'persistentConnection': false,
    'allowCompression': true,
    'followRedirect': flase,
    'maxRedirects': 16,
    'httpVersion': 2,
    'http2Required' : true,
    'rewriteHost': false
};
var HttpUserAgent = new urlopen.HttpUserAgent(ua_options);

HttpUserAgent API

HttpUserAgent 对象提供以下 API 来管理特定于 HTTP的用户代理程序。

所有 API 规范都使用假定由 urlopen.httpUserAgent() 类构造函数定义的 HttpUserAgent 对象。

HttpUserAgent.prototype.get()

返回 HttpUserAgent 对象的特定属性值或返回 HttpUserAgent 对象。

语法

HttpUser代理程序。prototype.get([name])
名称HttpUserAgent 对象中的属性名。 有效属性在 urlopen.HttpUserAgent() API 的 ua_options 参数中定义。
指定属性名称时,将返回属性值。 否则,将返回 HttpUserAgent 对象。 指定无效属性名时,将返回 undefined

HttpUserAgent.prototype.set()

配置 HttpUserAgent 对象的特定属性。

语法

HttpUser代理程序。prototype.set(名称)
HttpUser代理程序。prototype.set({name: value})
名称HttpUserAgent 对象中的属性名。 有效属性在 urlopen.HttpUserAgent() API 的 ua_options 参数中定义。
要分配给属性的值。

urlopen.open() ,用于与目标服务器连接

urlopen.open() API 可以与目标服务器建立非流式连接。 urlopen.open() API 可以配置用户代理程序以对本地服务发起请求,以建立与目标服务器的连接。

语法

var urlopen = require ('urlopen');
urlopen.open(选项回调);
选项作为目标服务器的 JSON 对象或单个 URL 规范分组的多个属性。
回调指定要在 urlopen.open() 连接到目标,将数据发送到目标并解析响应头之后调用的异步函数。 回调采用 function (error, response) { } 格式。

目标服务器的 URL 支持 HTTP和 HTTPS 协议。 对于 HTTPS 协议,请确保 TLS 概要文件中的验证凭证包含正确的权限。 权限是目标服务器的服务器端证书或中间认证中心。

建立连接时,将读取来自响应服务器的响应以获取数据。 通过使用下列其中一个读取 API 来获取数据。 假定 response 对象由 urlopen.open() API 初始化。
  • response.readAsBuffer()
  • response.readAsBuffers()
  • response.readAsJSON()
  • response.readAsXML()

当 HTTP 或 HTTPS urlopen.open() 调用完成时,将断开与目标的连接。 发生错误时,连接会自动关闭。 不需要执行额外的操作来关闭连接。 response.discard()response.disconnect() API 可以废弃数据并断开打开的连接。

示例

  • 打开连接并将响应作为缓冲区对象读取。
    var urlopen = require('urlopen');
    
    var options = {
                target: 'http://example.com/mydoc.json',
                method: 'post',
               headers: { 'X-My-Header1' : 'value1' , 'X-My-Header2' : 'value2' },
           contentType: 'text/plain',
               timeout: 60,
      sslClientProfile: 'aliceProxyForwardTrusted',
                  data: "Hello DataPower GatewayScript"};
    
    urlopen.open(options, function(error, response) {
      if (error) {
        // an error occurred during the request sending or response header parsing
        session.output.write("urlopen error: "+JSON.stringify(error));
      } else {
        // get the response status code
        var responseStatusCode = response.statusCode;
        var responseReasonPhrase = response.reasonPhrase;
        console.log("Response status code: " + responseStatusCode);
        console.log("Response reason phrase: " + responseReasonPhrase);
        // reading response data
        response.readAsBuffer(function(error, responseData){
          if (error){
            throw error ;
          } else {
            session.output.write(responseData) ;
          }
        });
      }
    });
  • 使用 HttpUserAgent 对象来建立与目标服务器的连接,并将响应作为缓冲区对象读取。
    var urlopen = require(’urlopen’);
    // define the http-specific user agent properties
    var ua_options = {    
        'persistentConnection': true,
        'allowCompression': false,
        'followRedirect': true,
        'maxRedirects': 8,
        'http10Only': false,
        'rewriteHost': false
    };
    var HttpUserAgent = new urlopen.HttpUserAgent(ua_options);
    // define the urlopen options
    var options = {
        target: 'http://127.0.0.1:42410/echo',
        //If the target is HTTPS like 'https://127.0.0.1:42409/echo', supply a TLS client profile
        //sslClientProfile: 'aliceClientProfile'
        method: 'post',    
        headers: { 'X-My-Header1' : 'value1', 'X-My-Header2': 'value2' },
        contentType: 'application/json',
        timeout: 60,    
        data: "Hello DataPower GatewayScript",
        agent: HttpUserAgent
    };
    urlopen.open(options, function(error, response) {
      if (error) {
        // an error occurred during the request sending or response header parsing
        session.output.write("urlopen error: "+JSON.stringify(error));
      } else {
        // get the response status code
        var responseStatusCode = response.statusCode;
        var responseReasonPhrase = response.reasonPhrase;
        console.log("Response status code: " + responseStatusCode);
        console.log("Response reason phrase: " + responseReasonPhrase);
        // reading response data
        response.readAsBuffer(function(error, responseData){
          if (error){
            throw error ;
          } else {
            session.output.write(responseData) ;
          }
        });
      }
    });

urlopen.open() 以在 DataPower Gateway 上打开文件

用于在 DataPower 文件系统中打开文件的 urlopen.open() API。

语法

var urlopen = require ('urlopen');
urlopen.open(选项回调);
选项一组属性,分组为目标文件的 JSON 对象或单个 URL 规范。
回调指定要在 urlopen.open() 连接到目标,将数据发送到目标并解析响应头之后调用的异步函数。 回调采用 function (error, response) { } 格式。
urlopen.open() API 将打开使用 target 属性指定的文件。 本地文件访问通过协议方案进行区分。
  • 只能使用 local:store:temporary: 协议方案来访问文件。
  • 文件引用区分大小写。 例如, local:///myArea/myFile.XMLlocal:///myArea/myFile.xml不同。

示例

  • 访问 local:///mylocal_directory中的 mylocal_file.xml ,以 Buffer 对象形式读取响应,并将数据写入输出上下文。
    var urlopen = require('urlopen');
    urlopen.open("local:///mylocal_directory/mylocal_file.xml", function (error, response) {
      if (error) {
        session.output.write("openCallback error: " + error.errorMessage+"\n");
      }
      else {
        if (response.statusCode == 200) {
          // You have a 200, so you can read the file
          response.readAsBuffer (function (error, data) {
            session.output.write(data);
          });
        }
      }
    });
  • 尝试访问不存在的文件将返回 404 File not found 状态码。
    var urlopen = require('urlopen');
    urlopen.open("local:///nonexisting.txt", function (error, response) {
      if (error) {
        session.output.write("openCallback error: " + error.errorMessage+"\n");
      }
      else {
        if (response.statusCode != 200) {
          // in this case, a non-200 statusCode indicates a problem reading the file
          session.output.write("Unable to open the file, statusCode: " +
                                response.statusCode + ", reasonPhrase: " +
                                response.reasonPhrase);
          response.disconnect();   // Optional: You can call response.disconnect()
                                   // to do an explicit disconnection. Without this
                                   // call, urlopen does an implicit disconnection
        }
        else {
          response.readAsBuffer(function(readError, data) {
            if (readError) {
              session.output.write("read file error: " + readError.toString());
            }
            else {
              session.output.write(data);
            }
          });
        }
      }
    });
  • 使用 JSON 对象来指定 urlopen.open() API 的 options 参数。
    var urlopen = require('urlopen');
    var open_options = {
      // the target URL
      target: 'local:///mylocal_directory/mylocal_file.xml',
      // method is optional, default is GET
      method: 'GET'
    };
    
    urlopen.open(open_options, function (error, response) {
      if (error) {
        session.output.write("openCallback error: " + error.errorMessage+"\n");
      }
      else {
        if (response.statusCode != 200) {
          // in this case, a non-200 statusCode indicates a problem reading the file
          session.output.write("Unable to open the file, statusCode: " +
                                response.statusCode + ", reasonPhrase: " +
                                response.reasonPhrase);
          response.disconnect(); // optional, urlopen will do an implicit disconnect()
        }
        else {
          response.readAsBuffer(function(readError, data) {
            if (readError) {
              session.output.write("read file error: " + readError.toString());
            }
            else {
              session.output.write(data);
            }
          });
        }
      }
    });

IBM MQ 消息的 urlopen.open() 格式

urlopen.open() API 可以动态或静态地在 GatewayScript 操作中发送和接收 IBM MQ 消息。 您可以使用特定于 IBM MQ 协议的 urlopen.open() API 的 options 参数中定义的各种属性动态创建的 URL 。 您还可以使用可以在 urlopen.open() API 的 options 参数或非选项规范中定义的完全指定的 URL 。

语法

var urlopen = require ('urlopen');

var 选项 =
{
  目标: targetURL,
  数据: message,
  头: mqHeaders, 
  代理程序: UserAgentparameter1: parameter_value1
  parameter2: parameter_value2
  :
  parametern: parameter_valuen};

var mqHeader = {"MQMD": {
                    "版本": { $ , "1" },
                    "格式": { $ , "MQSTR" }
               } };
urlopen.open(选项回调);
var urlopen = require ('urlopen');
urlopen.open(targetURL回调);
mqHeadersmqHeader 标识一个或多个 header_name 属性 (例如 MQMD) 以及包含与指定头相关的一组 header_fields 的关联头值。 头可以指定为 JSON 对象或 XML 字符串。
targetURLurlopen 调用的 IBM MQ URL 的名称。 协议可以是 dpmqidgmqmq。 如果将 targetURL 指定为 JSON 属性,那么 URL 可以是完整的,也可以是部分的。 JSON 对象中的参数属性提供了更多规范。
UA可以对本地服务发起请求以建立与指定目标服务器的连接的 UserAgent 对象。
选项由用于指定 IBM MQ 行为的属性组成。 GatewayScript 的属性与 dp:url-open 扩展元素的相应属性相同。 这包括 IBM MQ 队列管理器的静态和动态属性。 可用的属性列表是来自 dp:url-open IBM MQ 扩展元素的查询参数和动态 mq:/// 队列管理器属性的属性。
回调指定要在 urlopen.open() 连接到目标,将数据发送到目标并解析响应头之后调用的异步函数。 回调采用 function (error, response) { } 格式。
  • 有关 options的更多信息,请参阅 urlopen.open() API 以及特定于 dp:url-open() 通用和 IBM MQ 的扩展元素。
  • IBM MQ 断开连接基于队列管理器的高速缓存超时属性。
  • 在 GatewayScript中, options 参数采用指定关键字和值 (parameter: value) 的 JSON 对象的格式。 options 中包含的属性不区分大小写。 在 XSLT 中, options 中包含的属性采用参数赋值的形式 (parameter=value)。 对于 options中包含的某些属性,该属性的任何值都将定义其行为。 要不使用此行为,请勿包含此属性。 有关更多信息,请参阅 dp:url-open() IBM MQ 扩展元素主题。
  • 提供非选项表单是为了与其他 urlopen.open 协议保持一致。 但是,由于缺省 MQMD 头和无法指定消息内容,因此它的用处有限。
  • GatewayScript 将驼峰案例命名格式用于属性和参数。 这些参数用于静态和动态 IBM MQ URL。 这些属性指定动态 IBM MQ URL 的队列管理器连接属性。 有关这些参数的列表和描述,请参阅 IBM MQ 文档中的 url-open
    属性
    userName, channelName, channelTimeout, channelLimit, size, mqcspUserId, mqcspPassword
    参数
    requestQueue, replyQueue, timeOut, transactional, sync, gmo, pmo, parseHeaders, setReplyTo, asyncPut, browse, contentTypeHeader, contentTypeXPath, parseProperties, publishTopicString, selector, subscribeTopicString, subscriptionName
  • 如果未在 options.headers中定义 MQMD 头,那么将使用缺省 MQMD 头。 MQMD 缺省值的 MsgType 字段为 8。 此用法意味着将使用数据报,并且不需要任何应答。 有关 MQMD 缺省值和其他参数描述的更多信息,请参阅 IBM MQ 文档并搜索 MQMD。
  • 可以单独或在目标 URL上指定 options 参数。 例如,以下 options 定义等效
      options = { target: 'idgmq://' + session.parameters.qm + '/?',
         requestQueue: session.parameters.requestQAlwaysReply,
           replyQueue: session.parameters.replyQ,
        transactional: true,
                 sync: true,
              timeOut: 10000,
              headers: { ... },
                 data: putData };

    options = { target: 'idgmq://' + session.parameters.qm + '/?RequestQueue=' 
                 + session.parameters.requestQAlwaysReply + ';ReplyQueue=' + session.parameters.replyQ 
                 + ';Transactional=true;Sync=true;TimeOut=10000',
               headers: { ... },
                  data: putData };

    单独指定属性以及在目标 URL 上指定属性都会导致异常。

  • IBM MQ返回的状态码。
    0
    成功返回。
    2xxx
    返回错误。
  • 有关 IBM MQ 头的更多信息,请参阅 IBM MQ 文档并搜索 MQMD 或搜索 MQI 中使用的数据类型

示例

  • options JSON 对象格式对 MQ 进行的样本调用。 options 对象中的 headers 标签信息的格式与其他标签的信息的格式不同。
    var urlopen = require ('urlopen');
    var putData = '<MQRequest>Hello World</MQRequest>'; 
    
    var options =
    {
        target: 'mq://192.0.2.0:1414?QueueManager=QM1;UserName=mqm;Channel=QM1.SVRCONN;ChannelTimeout=10;'
                  + 'channelLimit=100;Size=1024000;RequestQueue=queue1;ReplyQueue=queue2',
      
         data : putData,
      headers : { MQMD   : { // JSON object for specified header_name
                                MQMD: { // JSON object for the MQMD header
                                       StructId : { $ : 'MD' } ,
                                        Version : { $ : '1'} ,
                                      }
                            } 
                  }
    };
    
    urlopen.open (options, function (error, response) {} );
  • 一个示例显示如何设置和使用更复杂的 IBM MQ 头。
    var urlopen = require('urlopen');
    var putData = '<MQRequest>Hello World</MQRequest>'; 
    
    var urlopenHeaders = {
            // supply an MQMD header
            MQMD : {     // This MQMD is the header name.
                    MQMD: {  // JSON object for the MQMD header
                  StructId : { $ : 'MD' },
                   Version : { $ : '1' },
                    Format : { $ : 'MQHRF2' },
                    MsgType : { $ : '1' },
               ReplyToQMgr : { $ : session.parameters.qm },
                  ReplyToQ : { $ : session.parameters.replyQ },
                    Expiry : { $ : '10000' },
               Persistence : { $ : '1' },
                  Priority : { $ : '10' },
               PutApplType : { $ : '6' },
               PutApplName : { $ : 'My Datapower IBM MQClient' }, 
            ApplOriginData : { $ : 'testUrlOpenMPGW' },
          ApplIdentityData : { $ : 'mqUrlOpenDemo.js' } }
                   },
             // supply an MQRFH2 header
             MQRFH2 : { 
               MQRFH2: {
                     Format: { $ : 'MQSTR' },
              NameValueData: {
                       NameValue: [
                                    { mcd : { property1 : { $ : '1111' } } },
                                    { jms : { property2 : { '@dt': 'string', $ : 'value2'} } },
                                    { usr : { group : {
                                                 property3 : { $ : 'value3' },
                                                 property4 : { $ : 'value4'} } } }
                                  ] }
                   }
             }
     };
    
      var options = {
                         target : 'idgmq://' + session.parameters.qm + '/?RequestQueue='
                             + session.parameters.requestQ,
                       headers : urlopenHeaders,
                        data : putData,
               replyQueue : session.parameters.replyQ,
                      pmo : 2052  // MQPMO_NO_SYNCPOINT (4) + MQPMO_SET_ALL_CONTEXT (2048) };
    
     try {
           urlopen.open(options, function(connectError, response) {
                 if (connectError) {    
                       var errorMessage = connectError + 'errorCode='
                                            + connectError.errorCode.toString(16);
                       console.error(errorMessage);
                       session.output.write(errorMessage);
    
                  } else {
                       var responseCode = response.statusCode; 
                       if (responseCode == 0) {
                             console.info('Received MQ ' + response.statusCode
                                           + ' for target ' + options.target); 
                             response.readAsXML(function(readAsXMLError, xmlDom) {
                                  if (readAsXMLError) {
                                      var errorMessage = 'Error on readAsXML: ' + readAsXMLError;
                                      console.error(errorMessage);
                                      response.readAsBuffer(function(readAsBufferError, buffer) {
                                           if (readAsBufferError) { 
                                                 var errorMessage = 'Error on readAsBuffer: '
                                                                     + readAsBufferError;
                                                 console.error(errorMessage);
                                                 session.output.write(errorMessage);
                                           } else {
                                                 console.info('MQ Response headers: ' + response.headers);
                                                 session.output.write(buffer);
                                           }
                                });
                        } else { 
                            console.info('MQ Response headers: ' + response.headers);
                            session.output.write(xmlDom);
                        }
                   });
               } else {
                  var errorMessage = 'Received MQ ' + response.statusCode
                                    + ' for target ' + options.target;
                  session.reject(errorMessage);
               }
            }
        }); 
    } catch (err) {
         var errorMessage = 'Thrown error on urlopen.open for target ' + options.target + ': '
                             + err.message + ', error object errorCode=' + err.errorCode.toString(16);
         session.reject(errorMessage);}
  • 如何为 MQMP 头声明 options JSON 对象的示例。
    var urlopenMQMPHeaders = {
            // supply an MQMD header
            MQMD : {    // The property name 'MQMD' is the header name.
                    MQMD: {   // This 'MQMD' represents the root property.
                              StructId : { $ : 'MD' },
                               Version : { $ : '2' },
                                Format : { $ : 'MQSTR' },
                               MsgType : { $ : '1' },
                           ReplyToQMgr : { $ : session.parameters.qm },
                              ReplyToQ : { $ : session.parameters.replyQ },
                                Expiry : { $ : '10000' },
                           Persistence : { $ : '1' },
                              Priority : { $ : '10' },
                           PutApplType : { $ : '6' },
                           PutApplName : { $ : 'My Datapower IBM MQClient' },
                        ApplOriginData : { $ : 'testUrlOpenMPGW' },
                      ApplIdentityData : { $ : 'testUrlOpen.js' }
                          }
                   },
            // supply an MQMP header
            MQMP : {   // The property name 'MQMP' is the header name.
                       MQMP: { // This 'MQMP' represents the root property.
                                     Property : [ // an array of property
                                             { '@name' : 'car.brand', '@type':'string', $ : 'DataPower'},
                                             { '@name' : 'car.color', '@type':'string', $ : 'GREEN'},
                                             { '@name' : 'car.year', '@type':'int32', $ : '2005' }
                                                ]
                             }
                   }
    };
    options = {
        target: 'idgmq://' + session.parameters.qm + '/?RequestQueue=GATEWAYSCRIPT.PROPERTIES.REQUEST' 
                          + ';ReplyQueue=' + session.parameters.replyQ,
       headers: urlopenMQMPHeaders,
          data: putData,
           pmo: 2052  // MQPMO_NO_SYNCPOINT (4) + MQPMO_SET_ALL_CONTEXT (2048)};
    };

response 对象

response 对象表示回调函数中网络连接的响应。 在所有使用 response 对象的 API 规范中,如果未指定,那么假定 response 对象由 urlopen.open() API 初始化。 response 对象是 callback 函数的第二个参数,它是 urlopen.open() API 的参数。


response.discard()

废弃响应。 此 API 指示 urlopen.open() API 有效接收但丢弃响应消息的字节数。 您可以从响应对象访问头元数据。 根据错误,可能没有要废弃或断开连接的错误。 response.discard() 的一个重要用途是获取失败响应的状态码。

语法

response.discard (function (error) { })
错误response.discard() API 期间发生错误时的错误对象。

response.disconnect()

未返回响应内容。 此 API 指示 urlopen.open() API 立即停止后端连接。 对于除 IBM MQ 响应之外的响应,此操作可消除读取大型有效内容的等待时间,但如果使用持久连接,可能会产生不利影响。

语法

response.disconnect ()

response.get()

读取响应头。

语法

response.get ([headername])
response.get (optionsheadername)
头名指定用于检索特定响应头的可选头名称。
选项分组为 JSON 对象的一组属性。

当指定了 headername 参数时, response.get() API 将返回特定响应头。 例如, response.get('h1') 检索 h1 头,这相当于 response.headers.h1response.headers['h1']

  • 如果未提供头名称,那么 response.get() 等同于包含整个响应头集合的 response.headers
  • response.get(headername) 表单读取非结构化 (原始) 头。 response.get(options, headername) 表单读取 type选项中指定的结构化头。 有关结构化和非结构化头的更多信息,请参阅头模块。
获取 IBM MQ 响应头。
var urlopen = require('urlopen');  // access the module
urlopen.open (options, function (error, response) {

//  get the response as a JSON object representing an MQ header structure
var structured = response.get({type: 'mq'}, 'MQMD');  

response.headers

将响应头的整个集合读取到 JSON 对象中。

语法

response.headers

response.readAsBuffer()

将响应读入 Buffer 对象。

语法

response.readAsBuffer (function (errorbuffer) { })
错误response.readAsBuffer() API 期间发生错误时的错误对象。
缓冲区包含成功 response.readAsBuffer() API 读取的数据的缓冲区位置。
response.readAsBuffer() API 将数据作为缓冲区对象读取。 如果读取成功,那么数据将成为缓冲区变量 buffer的值。 否则, GatewayScript 错误对象 error 描述该错误。

response.readAsBuffers()

将响应读入 Buffers 对象。

语法

response.readAsBuffers (function (errorbuffers) { })
错误response.readAsBuffers() API 期间发生错误时的错误对象。
缓冲区包含成功 response.readAsBuffers() API 读取的数据的 Buffers 对象。
response.readAsBuffers() API 将数据作为 Buffers 对象读取。 如果读取成功,那么数据将成为 buffers 变量的值。 否则, GatewayScript 错误对象 error 描述该错误。

response.readAsJSON()

将响应读入 JSON 对象。

语法

response.readAsJSON (function (errorjson) { })
错误response.readAsJSON() API 期间发生错误时的错误对象。
json包含成功 response.readAsJSON() API 读取的数据的 JSON 对象。
response.readAsJSON() API 读取数据并将其解析为 JSON 对象。 如果读取成功,那么数据将成为 json 变量的值。 否则, GatewayScript 错误对象 error 描述该错误。

response.readAsXML()

将响应读入 XML 对象。

语法

response.readAsXML 函数 (errorxml) { })
错误response.readAsXML() API 期间发生错误时的错误对象。
xml包含由成功 response.readAsXML() API 读取的数据的 XML 对象。
response.readAsXML() API 将数据作为 NodeList读取。 如果读取成功,那么数据将成为 nodelist 变量的值。 否则, GatewayScript 错误对象 error 描述该错误。

response.reasonPhrase

urlopen.open() 响应中读取原因短语。 原因短语仅可用于 HTTP 目标。


response.statusCode

urlopen.open() 响应中读取状态码。


response.types

返回 urlopen.open() 响应头的受支持结构类型的数组。

获取响应头的类型。
var urlopen = require('urlopen');

var options = {
target: 'idgmq://qmgr/?RequestQueue=q1', 
// Note that inMQMD and inMQRFH2 headers are in the same format
// as shown in urlopenMQMPHeaders in a previous example.
headers: {
   'MQMD': inMQMD,
   'MQRFH2': inMQRFH2
  },
} ;
urlopen.open (options, function (error, response) {
// consume response MQMD header as JSON
var outMQMD = response.get({type: 'mq'}, 'MQMD');
// returns ['mq']
var types = response.types;
...
});