bad request with UrlFetchApp

前端 未结 1 1925
不知归路
不知归路 2020-12-22 07:40

Looking for some help connecting to this service and returning the xml.

Here are the instructions (from here):

The state of the inputs and rel

相关标签:
1条回答
  • 2020-12-22 08:18

    There are a couple of coding errors that you can easily take care of:

    1. In the Authorization header you need a space after "Basic".
      Authorization : "Basic " + Utilities.base64Encode(username+':'+password)

    2. urlFetchApp.fetch() returns an HTTP Response object, so you need to extract the contents for parsing.
      var result = UrlFetchApp.fetch(url, options);
      var state = result.getContentText();

    3. You aren't returning anything from your parse() function.

    4. You should check result.getResponseCode() after .fetch(), and handle errors before proceeding with parsing.

    That said, I keep getting Bad request: http://75.65.130.27/state.xml errors, so something is still not right. This is an HTTP 400 response, and google's servers don't return anything to the script debugger to dig into it. You should check the username & password, although I'd expect a 401-Unauthorized response if they were wrong. I tried including a payload of relay1State=2, and got the same Bad request result. If you can capture the HTTP Request hitting your server, there may be a clue to what is malformed. This could also be the result of a firewall.

    Once that's sorted, this tutorial should help with the XML Parsing.

    Here's my edit of your code:

    function webRelay(){
      var url = 'http://75.65.130.27/state.xml';
      var username = "none";
      var password = "webrelay";
    
      var headers =
      {
        Authorization : "Basic " + Utilities.base64Encode(username+':'+password)
      }
    
      var options =
      {
        "method" : "get",
        "headers": headers
      };
    
      // Getting "bad request" here - check the username & password
      var result = UrlFetchApp.fetch(url, options);
      var state=result.getContentText(); 
    
      // You should check state.getResponseCode()
    
      Logger.log('1: '+state);
      Logger.log(parse(state));
    }
    
    function parse(txt) {
      var doc = Xml.parse(txt, true);
      return doc;                            // Return results
    }
    
    0 讨论(0)
提交回复
热议问题