在SWIFT + ios中请求json时出错

时间:2015-01-03 06:27:21

标签: ios json swift http-post

我正在通过json请求一些数据,我是SWIFT for iOS的新手,所以我不知道我的代码中有什么问题:

var URL="http://X.X.X.X.X/Api/UserManagement/getMobileUser";
    var UserId=uname.text;
    var pword=passwd.text;
    var PostData: NSString = "{\"data\":{},\"action\":\"System\",\"method\":\"getMobileUser\",\"username\":\" mpc01\",\"password\":\"mpc01\",\"type\":\"rpc\",\"tid\":\"144\"}"
    let request = NSMutableURLRequest(URL: NSURL(string: URL)!)
    request.HTTPMethod = "POST"

    let postString = PostData
    //var st:NSData = PostData.dataUsingEncoding(NSUTF8StringEncoding)!
   // request.HTTPBody = PostData.dataUsingEncoding(NSUTF8StringEncoding)

    request.HTTPBody = (postString as NSString).dataUsingEncoding(NSUTF8StringEncoding)


   //let data = (postString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            println("error=\(error)")
            return
        }

        println("response = \(response)")


        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = \(responseString)")

    }
    task.resume()

我得到的回应是:

response = {URL:http://X.X.X.X/Api/UserManagement/getMobileUser} {status code:500,headers {     "缓存控制" =" no-cache&#34 ;;     " Content-Length的" = 36;     "内容类型" =" application / json;字符集= UTF-8&#34 ;;     日期="星期六,03 Jan 2015 06:11:51 GMT&#34 ;;     Expires =" -1&#34 ;;     Pragma =" no-cache&#34 ;;     Server =" Microsoft-IIS / 7.5&#34 ;;     " X-ASPNET-版" =" 4.0.30319&#34 ;;     " X供电-通过" =" ASP.NET&#34 ;; }} responseString = Optional({" Message":"发生错误。"})

1 个答案:

答案 0 :(得分:-1)

我遇到类似的问题,尝试向MailGun发送一些我在应用中实现的自动电子邮件。

我能够通过大型HTTP响应使其正常工作。我把完整的路径放到Keys.plist中,这样我就可以将我的代码上传到github并将一些参数分解为变量,这样我就可以在以后的程序中设置它们。

// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?

if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
    keys = NSDictionary(contentsOfFile: path)
}

if let dict = keys {
    // variablize our https path with API key, recipient and message text
    let mailgunAPIPath = dict["mailgunAPIPath"] as? String
    let emailRecipient = "bar@foo.com"
    let emailMessage = "Testing%20email%20sender%20variables"

    // Create a session and fill it with our request
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler@<my domain>.com%3E&to=reservations@<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)

    // POST and report back with any errors and response codes
    request.HTTPMethod = "POST"
    let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        if let error = error {
            print(error)
        }

        if let response = response {
            print("url = \(response.URL!)")
            print("response = \(response)")
            let httpResponse = response as! NSHTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
    task.resume()
}

Mailgun Path在Keys.plist中作为名为mailgunAPIPath的字符串,其值为:

https://API:key-<my key>@api.mailgun.net/v3/<my domain>.com/messages?

希望这有帮助!