2016-03-24 146 views
0

我嘗試使用NSMutableURLRequest創建POST請求,但將NSData對象傳遞給其HTTPBody的行爲與預期不符。使用NSJSONSerialization.dataWithJSONObject嚴重構建POST正文請求

這裏是我做的:

guard let url = NSURL(string: endpoint) else { 
     print("Error: Cannot create URL") 
     return nil 
    } 
    do { 
     let params = try NSJSONSerialization.dataWithJSONObject(options, options: []) 

     let urlRequest:NSMutableURLRequest = NSMutableURLRequest(URL: url) 
     urlRequest.HTTPMethod = method 

     if method != "GET" { 
      urlRequest.HTTPBody = params 
     } 

     return urlRequest 

    } catch { 
     print("Error: Cannot parse options data into JSON") 
     return nil 
    } 

這裏是我所得到的:

#<Hashie::Mash {"token":"MVgutecI0y5AzJ8KcIgkxT56mwEh","email":"[email protected]","password":"adichris"}=nil> 

我的服務器是用Ruby編寫的。這裏是我取,

puts params.inspect 
+1

那麼究竟是什麼問題呢?你會得到什麼錯誤?你知道params中有一個純文本密碼嗎? – SamuelD

+0

@SamuelD我沒有錯誤。問題是我沒有在我的請求中獲得格式正確的JSON。關於密碼,它無處使用,但感謝注意! –

回答

2

既然你要發送JSON必須返回之前請求的Content-Type頭設置爲application/json

request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
+0

我知道這很簡單。謝謝! –