JSON password

petter.sundin@flir.sepetter.sundin@flir.se
Hello!
I'm trying to get a JSON response with:
$response = file_get_contents('http://192.168.254.177/probe_update.json');
But I only get the error:
Warning: file_get_contents(http://192.168.254.177/probe_update.json): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized in C:\wamp64\www\json\index.php on line 12

I suspect this is due to the page requires a password, but how do one send a password with a file_get_contents call?

Anyone with experience working with ServesCheck JSON page?

Thanks!

Kind regards
Petter

Comments

  • AdministratorAdministrator
    edited March 2018
    Not sure of your programming language but for example in PHP you would pass on the username and password as follows:
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");

    For javascript you could use following Jquery function
    $.ajax
    ({
    type: "GET",
    url: "url.json",
    dataType: 'json',
    async: false,
    headers: {
    "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
    },
    data: '{ "comment" }',
    success: function (){
    alert('Thanks for your comment!');
    }
    });
  • petter.sundin@flir.sepetter.sundin@flir.se
    Thank you very much!

    If someone else have the same issues, this is how I did:

    url = "http://192.168.254.177/probe_update.json";
    $username = 'admin';
    $password = 'admin';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

    $result = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);

    $data = json_decode($result, true);

    foreach ($data["probe_update"] as $item)
    {
    echo "Probe".$item["probe_id"].": ";
    echo $item["value"][0];
    echo "
    ";
    }
  • broome_garybroome_gary
    edited June 2018
    For those it helps, here's pettersundin 's script in Python:
    import requests url = "http://192.168.254.177/probe_update.json" username = "admin" password = "admin" result = requests.get(url, auth=(username, password)) data = result.json() for item in data['probe_update']:     print("Probe {0}: {1}".format(item['probe_id'], item['value']))
This discussion has been closed.