2014-08-27 109 views
1

我還沒有能夠發送一個迅速的post-request到一個接受字符串的服務器。服務器不接受JSON數據。蘋果庫中是否有任何方法?我找不到任何。用字符串發送後請求

或者你甚至可以告訴我怎麼寫這樣的方法?

let url = NSURL(string: "myUrl") 
var session = NSURLSession.sharedSession() 
let request = NSMutableURLRequest(URL: url) 
    request.HTTPMethod = "POST" 
var params = "login_act:'myUsername'&login_pwd:'myPassword'" 

var err: NSError? 
request.HTTPBody = NSJSONReadingOptions. 
// The following method call does not accept the params variable type, although I need to send a String 
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) 
request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
request.addValue("application/json", forHTTPHeaderField: "Accept") 

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
    println("Response: \(response)") 
    var strData = NSString(data: data, encoding: NSUTF8StringEncoding) 
    println("Body: \(strData)") 

任何幫助表示讚賞!

回答

3

如果服務器不接受JSON那麼什麼是設置頁眉內容類型應用程序/ JSON的目的。您有兩個選項,可以將內容作爲json發送,也可以作爲表單提交發送發佈請求。我會告訴你兩種可能的方式,

第一個只是張貼表單參數到url,它不接受json而是接受url編碼的表單參數。

let url = NSURL(string: "myUrl") 
var session = NSURLSession.sharedSession() 
let request = NSMutableURLRequest(URL: url) 
    request.HTTPMethod = "POST" 
var params = "login_act=myUsername&login_pwd=myPassword" 
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) 
var err: NSError? 

request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
    println("Response: \(response)") 
    var strData = NSString(data: data, encoding: NSUTF8StringEncoding) 
    println("Body: \(strData)") 
}) 

其他方法,如果你的服務器接受json參數,那麼這個方法和你所做的很相似。

let url = NSURL(string: "myUrl") 
var session = NSURLSession.sharedSession() 
let request = NSMutableURLRequest(URL: url) 
    request.HTTPMethod = "POST" 
var params = ["login_act":"myUsername", "login_pwd":"myPassword"] 

var err: NSError? 
// The following method call does not accept the params variable type, although I need to send a String 
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) 
request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
request.addValue("application/json", forHTTPHeaderField: "Accept") 

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
    println("Response: \(response)") 
    var strData = NSString(data: data, encoding: NSUTF8StringEncoding) 
    println("Body: \(strData)") 
}) 
+0

我需要使用你的第一個建議。但這些參數不包含在您的請求中。我怎麼做? – 2014-10-05 20:33:50

+0

請參閱我的編輯。 – Sandeep 2014-10-06 08:35:06

相關問題