NSURL oddity

So I’m looking to move an app away from using do shell script for curl operations.

I’m hitting something that seems odd, wherein when I create a URL with NSURL’s URLWithString, what I’m getting back is the result of the URL on the website, not a URL object?

This isn’t bad in and of itself for GET operations, but if it’s a URL for a post, where there’s nothing returned when "running’ the URL, then I get missing value.

I think I’m missing something?

You probably want to be using NSURLSession’s or NSURLConnection’s methods and related classes.

Of the two, NSURLConnection is deprecated, but I suspect it will be supported for a while. And it’s easier to use from AppleScript, partly because it has a synchronous option. Simpler stuff can be done like this:

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set theNSURL to current application's |NSURL|'s URLWithString:theString
set theNSURLRequest to current application's NSURLRequest's alloc()'s initWithURL:theNSURL cachePolicy:(current application's NSURLRequestReloadIgnoringCacheData) timeoutInterval:5.0
set {theNSURLConnection, theResponse, theError} to current application's NSURLConnection's sendSynchronousRequest:theNSURLRequest returningResponse:(reference) |error|:(reference)

Okay, so next question, how do you set the HTTP Method (get/post) etc. I’ve tried a few options, none of them seem to be working. (lots of unrecogonized selectors)

You’ll find quite a few examples here:

http://piyocast.com/as/

The site is in Japanese, but obviously the code isn’t, and the site is searchable.

I’ve wrote various REST API calling code. NSURLSession is not faster than NSURLConnection.
NSURLSession sample is here.

–Call Postmark’s spam detection API
http://piyocast.com/as/archives/3600

And other samples are …
http://piyocast.com/as/?s=NSURLSession

Shane could you explain the cache policy option you choose?

Thanks

Here’s some
Examples pasted from Piyumo site


  aRequest’s setHTTPMethod:"POST"
  aRequest’s setCachePolicy:(current application’s NSURLRequestReloadIgnoringLocalCacheData)
  aRequest’s setHTTPShouldHandleCookies:false
  aRequest’s setTimeoutInterval:timeoutSec
  –aRequest’s setValue:"gzip" forHTTPHeaderField:"Content-Encoding"–Does not work with this API & Method
  aRequest’s setValue:"application/json" forHTTPHeaderField:"Accept"
  aRequest’s setValue:"application/json; charset=UTF-8" forHTTPHeaderField:"Content-Type"


It’s pretty much what its name says: force reload ignoring anything cached.