1

I am trying to get some data from a URL which requires me to POST a JSON request. It works in the sense that I get some data back; just not the data I expected. I then used jsontest.com to test my code:

let url = NSURL(string: "http://echo.jsontest.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"

do {
    let params = ["echo": "abc"] as Dictionary<String, String>

    //... Just make sure that 'params' is a valid JSON object
    assert(NSJSONSerialization.isValidJSONObject(params))

    request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.PrettyPrinted)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

} catch {
    print("Error")
}

let session = NSURLSession.sharedSession()
dataTask = session.dataTaskWithRequest(request, completionHandler: {
    (data: NSData?, response: NSURLResponse?, error: NSError?) in

    if let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200,
        let data = data {

            let encodedData = NSString(data:data, encoding:NSUTF8StringEncoding)
            print("encodedData = \(encodedData!)")

    } else {
        print("Error")
    }
})

dataTask?.resume()

When I run this, I see the following output from jsontest.com:

encodedData = {"": ""}

where I expected

encodedData = {"echo": "abc"}

So, do I not understand correctly whether this is how jsontest.com works, or am I doing something wrong? (Obviously, I had similar problems using other JSON services.) Any comments are appreciated.

gbroekstg
  • 920
  • 1
  • 7
  • 16

3 Answers3

1

echo.jsontest.com doesn't work with a request body but with a request url, see www.jsontest.com/#echo for details.

Eric Aya
  • 68,765
  • 33
  • 165
  • 232
  • But that url comes with a note, saying "Note: GET requests are supported, though not recommended while using this service. You should use POST requests if possible." – gbroekstg Oct 02 '15 at 11:52
  • 1
    @gbroekstg They don't say that about echo. You missed the heading "Validate JSON" – JeremyP Oct 02 '15 at 12:23
0

Turns out @Eric D is right. I found another website to test my JSON posts on and that one worked fine. So the code is basically correct after all. I made the following changes:

let url = NSURL(string: "http://gurujsonrpc.appspot.com/guru")
let params = [ "method" : "guru.test", "params" : [ "GB" ], "id" : 123 ] as Dictionary<String, AnyObject>

and then I get the following response:

{"jsonrpc":"2.0","id":123,"result":"Hello GB!"}

Which is exactly what was expected. Thanks!

Community
  • 1
  • 1
gbroekstg
  • 920
  • 1
  • 7
  • 16
0

The correct URL is http://validate.jsontest.com

Also, I don't think you are constructing the POST request body correctly. See How are parameters sent in an HTTP POST request?

Community
  • 1
  • 1
JeremyP
  • 80,230
  • 15
  • 117
  • 158