Parsing User-Agent strings with a web service

I want to share a snippet of code.

In HTTP, a client identifies itself using the User-Agent header. That string is long and cryptic. To make sense of it you have to parse it. There are web services that can do this. Here is how you can invoke one of them.

ZnClient new
  http;
  host: 'useragentstring.com';
  queryAt: 'uas' put: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4';
  queryAt: 'getJSON' put: 'all';
  contentReader: [ :entity | NeoJSONReader fromString: entity contents ];
  get.

Since STON parsing is backward compatible with JSON, you can use that as well.

ZnClient new
  http;
  host: 'useragentstring.com';
  queryAt: 'uas' put: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4';
  queryAt: 'getJSON' put: 'all';
  contentReader: [ :entity | STON fromString: entity contents ];
  get. 

You will get back a nice dictionary with much more sensible key/value pairs.

Note that this is a public service. I think it would be polite and more efficient if you put a cache in front of it, like LRUCache.

Sven
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: