简体   繁体   中英

How do I extract parameters from an HTTP response header string?

I need to authenticate against a proxy server, and after the first HTTP request the I need to parse the proxy-authenticate header string to get the relevant values.

The response headers look something like this,

{ 'content-type': 'text/plain',
  'proxy-authenticate': 'Digest realm="zippy", qop="auth",nonce="c1e1c76b5df5a8cdc921b48d6a7b5493", algorithm="MD5", stale="false"',
   date: 'Thu, 21 Apr 2016 00:19:28 GMT',
   connection: 'close',
  'transfer-encoding': 'chunked' }

I want to extract the proxy-authenticate parameters (ie realm, qop, etc.), from the string.

It seems like there must be some super simple way to do this, but I'm just not finding it.

Simply extract your key from the JSON, and split the value by , . Then again split each value of resulting array using = .

$(document).ready(function() {
  var data = {
    'content-type': 'text/plain',
    'proxy-authenticate': 'Digest realm="zippy", qop="auth",nonce="c1e1c76b5df5a8cdc921b48d6a7b5493", algorithm="MD5", stale="false"',
    date: 'Thu, 21 Apr 2016 00:19:28 GMT',
    connection: 'close',
    'transfer-encoding': 'chunked'
  };

  var header = data['proxy-authenticate'];
  var contents = header.split(',');

  var pairs = {};
  $.each(contents, function(index, value) {

    var pair = value.split('=');
    pairs[pair[0]] = pair[1];
  });

  $('div').html(JSON.stringify(pairs));
});

Here is a demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM