netRequest()

The function netRequest allows you to use various methods to operate on the server.

Synopsis

int netRequest(string url, string verb, mapping|string|blob data [, mapping|string|blob &result]);

Parameter

Parameter Description
url

The URL (https, ftp and file - file only applies to local files).

Since the URL has to correspond to specific syntax rules, the QT implementation of the URL parser tries to correct errors in the syntax. See the section "QUrl::TolerantMode" in the description Qt - QURL Parsing Mode and Uniform Resource Identifier (URI)- Generic Syntax.

The function is terminated in case of an invalid URL and it returns -1.

verb

The verb, which defines the action done by the function.

Which verbs can be used depends on the server in use (for the verbs usable with the WinCC OA server see the function httpSetMethodHandler())

data

The parameter "data" contains the data that is sent to server. The parameter can be a mapping, a string or a blob. Thus, 3 parameter types can be used. If a mapping is used as data, the keys described in the following can be used.

A netRequest request receives an answer from the server (HTTPS protocol). The content of the answer can be passed in memory to the result mapping (see the description on the next row of this table) or you can you specify a target file via the "target" key in the data mapping. See the keys for the data mapping below.

  • "target" (string) ... an absolute path to a directory or to a file the content of the response is saved in. If you specify a directory path, the file name from the URL is added to the directory path to create a final file name. This file name is also saved in the "result" variable under key word "target". For the variable result see the description on the next row of this table. The file must be opened for reading or the function returns -1 and is terminated. A file is created if it does not exist.

  • "content" ... Specifies the content that is transmitted. Permitted data types are string and blob. e.g..:

    data["content"] = "some data to transmit"; //
                                                string data["content"] =
                                                (blob)"736F6D65206461746120746F207472616E736D6974"; //
                                                blob ############# "result" Row:
                                                result["target"]:
  • "headers" (mapping) ... Additional header that is transferred to the server during the communication. In the key "Content-Type" in the mapping that can be passed in the "headers"key, you can specify the MIME type of the data transmitted. If you do no specify the data type, the content is automatically detected and a content type header is used.

  • "ignoreSslErrors" ... If you pass a value unequal to dyn_string or an empty dyn_string, all SSL errors are ignored. All occurred SSL errors are, however, returned and you can find them in the result["sslErrors"] mapping. See the description of the result variable on the next row of this table and list of the SSL errors below the description. If you specify a dyn_string, you specify which SSL errors may be ignored. If there are other SSL errors, the function returns -1 and is terminated.

    data["ignoreSslErrors"] = ""; //All SSL errors are
                                                ignored data["ignoreSslErrors"] =
                                                makeDynString("CertificateUntrusted");
    //Ignore CertificateUntrusted errors
  • followRedirection" ...If you specify false for the bool parameter, the automatic "Redirection Handling" is deactivated. In the Redirection Handling, the HTTP protocol allows the server to send a "redirection" answer. Thereby, a client knows that the required resource is reachable under another URL. The function netGet follows these instructions by default. In order to avoid a redirection loop (e.g. A -> A oder A -> B -> C -> A, etc.), the number of answers is limited. If this number is exceeded, the function returns -1 ("RedirectionLoop" error) and is terminated. You can activate or deactivate the redirection handling by using the "followRedirection" key for the data mapping.

    e.g.:

    data["followRedirection"] = false; // automatic redirection deactivated

    data["followRedirection"] = true; // automatic redirection activated (default)

  • "sslConfig" ... the sslConfig is a mapping that contains the certificate information required for secure communication and contains the following keys:

    "localCertificate" (string) - PEM encoded certificate

    "privateKey" (mapping) - key and algorithminformation

    "key" (string) - private key in PEM encoded form.

    "algorithm"(string) - The used algorithm, possible values: "RSA", "DSA", "EC" (Elliptic Curve)

    Example

    A PEM-encoded certificate file can be loaded from the local disk as follows:

    fileToString(getPath(CONFIG_REL_PATH, "certificate.pem"), cert);

    and then the returned string can be passed as value for the key "localCertificate".

  • clearAccessCache...Flushes the internal cache of authentication data and network connections. Note that this key must only be specified for the data mapping. You do not need to specify a value for it.

  • clearConnectionCache ... Flushes the internal cache of network connections. In contrast to clearAccessCache the authentication data is preserved. Note that this key must only be specified for the data mapping. You do not need to specify a value for it.

result

The function netRequest receives an answer from the server and passes it to the result variable.

Thereby the following keys are optionally set. The keys with the text (always) are always set. See https://tools.ietf.org/html/rfc2616#section-6.1.1.

  • "headers" (always) ... Contains a mapping with key (header name) and value (header) pairs. It can also be empty.

    Example:.

    "Last-Modified" : "Mon, 09 Sep 2013 09:08:45 GMT"

    "Date" : "Wed, 16 Jul 2014 07:37:13 GMT"

    "Content-Length" : "1127"

    "Content-Type" : "image/png"

  • "content" (always) ... Contains the received data. The data type is string by default. You can specify the data type by using the variable data. If you specified a target file by using the "data" variable, the content here is always empty. See keyword "target" under data parameter above.

  • "url" (always) ... The URL that was used for the last query. It can differ from the original URL if a redirection answer is received from the server in the HTTP protocol (see Redirection Handling under data parameter on the row above).

  • "httpStatusCode", "httpStatusText" ... In an http/https communication the httpStatusCode and httpStatusText contain the last HTTP status code (int) and the respective "Reson Phrase" (string), e.g.

    "httpStatusCode" : 200

    "httpStatusText" : "OK"

    See https://tools.ietf.org/html/rfc2616#section-6.1.1

  • "target" ... If you specify a target file by using the data variable and the key word "target", the "target" key word here contains the absolute file path to the file/directory that contains the content of received answer. For data mapping see the row above in this table.

  • "errorString" ... The errorString contains a "readable" descriptive text if an error occurs in the communication. The parameters "error" and "errorString" are always set together. In this case, the function always returns -1.

  • "error" ... In case of errors, the function returns a string key word from the following list:

    - "RedirectionLoop" ... Too many redirects encountered

    - (see Redirection Handling)

    - All values from the enum are described on the following home page. The prefix string is not used, e.g. "ConnectionRefusedError"

    https://doc.qt.io/qt-5/qnetworkreply.html#NetworkError-enum

  • "sslErrors" ... If an SSL error occurs when establishing the communication, the list of SSL errors are passed in a mapping. The key in the mapping is a string key word from the following list. The value for the key is a descriptive text of the error. If the SSL errors are not ignored (see "ignoreSslErrors" under "data" mapping on the row above in this table), the function returns -1 and is terminated. Furthermore, the "result" variable does not contain any further keys.

    Possible SSL key words:

    "UnableToGetIssuerCertificate"

    "UnableToDecryptCertificateSignature"

    "UnableToDecodeIssuerPublicKey"

    "CertificateSignatureFailed"

    "CertificateNotYetValid"

    "CertificateExpired"

    "InvalidNotBeforeField"

    "InvalidNotAfterField"

    "SelfSignedCertificate"

    "SelfSignedCertificateInChain"

    "UnableToGetLocalIssuerCertificate"

    "UnableToVerifyFirstCertificate"

    "CertificateRevoked"

    "InvalidCaCertificate"

    "PathLengthExceeded"

    "InvalidPurpose"

    "CertificateUntrusted"

    "CertificateRejected"

    "SubjectIssuerMismatch"

    "AuthorityIssuerSerialNumberMismatch"

    "NoPeerCertificate"

    "HostNameMismatch"

    "NoSslSupport"

    "CertificateBlacklisted"

    "UnspecifiedError"

    The "result" mapping looks as follows:

    [mapping 1 items]

    "sslErrors" : mapping 4 items

    "CertificateUntrusted" : "The root CA certificate is not trusted for this purpose"

    "UnableToVerifyFirstCertificate" : "No certificates could be verified"

    "UnableToGetLocalIssuerCertificate" : "The issuer certificate of a locally looked up certificate could not be found"

    "HostNameMismatch" : "The host name did not match any of the valid hosts for this certificate"

  • "sslErrors2": Further information on the SSL errors such as certificate information.

    Possible key words:

    "errorString": Readable Errorstring "The certificate is self-signed, and untrusted"

  • "certificate": contains details about the certificate (if the error contains a certificate. Otherwise this "certificate" key does not exist)

    "digest": Unique identifier for each certifcate e.g. "52bfdc363d0832f1a38cfcb612779bf69e4c8d8d"

    "text": certificate tex

Return value

The function returns 0 if it was successfully executed and in case of errors -1.

Description

The function netRequest allows you use methods, if they are implemented at the server. The parameter "data" contains the data to be transmitted. The "data" parameter can be a mapping, a string or a blob. Thus, 3 parameter types can be used. If a mapping is used as data, keys described in the table above under "data" parameter are used. The "verb" parameter defines which action is used.

Use the function with HTTPs

// IgnoreSslErros is used and since an empty string is passed, all SSL errors are ignored.
                
main()
{
  mapping mappingResultOfNetRequestFunction;
  
  DebugN("netRequest function with method: PUT", netRequest("https://localhost:443", "PUT", makeMapping("content", "data to send", "followRedirection", false, "ignoreSslErrors", ""), mappingResultOfNetRequestFunction), mappingResultOfNetRequestFunction);
  delay(3); // As you might get a race condition in the LogViewer, while running server and client on the same host.
  DebugN("netRequest function with method: PATCH", netRequest("https://localhost:443", "PATCH", makeMapping("content", "data to send", "followRedirection", false, "ignoreSslErrors", ""), mappingResultOfNetRequestFunction), mappingResultOfNetRequestFunction);
}

// If you use our WinCC OA server and want to use for e.g. the "PATCH" method, this must be implemented by yourself via the httpSetMethodHandler.
// Like this example.
#uses "CtrlHTTP"

string methodCB(string clientIP, string url, int idx)
{
  string content;
  httpGetContent(idx, content);
  content = httpGetMethod(idx) + " " + content; // Return the same content and add the method, so we proof it worked.
  DebugN(content); // Show content on server log before sending, as it is only an example.
  return content;
}

//--------------------------------------------------------------------------------

string work(dyn_string names, dyn_string values, string user, string ip, dyn_string headerNames, dyn_string headerValues, int idx)
{
  string content;
  httpGetContent(idx, content);

  content = httpGetMethod(idx) + " " + content; // Return the same content and add the method, so we proof it worked.
  DebugN(content); // Show content on server log before sending, as it is only an example.
  return content;
}

//--------------------------------------------------------------------------------

main()
{
  httpServer(false, 80, 443); // Init http server.
  httpSetMethodHandler("PATCH", "methodCB");
  httpSetMethodHandler("PUT", "methodCB"); // This will be overwritten for demonstration purpos only.
  httpConnect("work", "/");
}

Assignment

HTTP functions

Availability

UI, CTRL