2014-10-14 23 views
107

Tôi đang cố gắng chạy một yêu cầu HTTP trong Swift, để POST 2 tham số cho một URL.Yêu cầu HTTP trong Swift với phương thức POST

Ví dụ:

Link: www.thisismylink.com/postName.php

Params:

id = 13 
name = Jack 

cách đơn giản nhất để làm điều đó là gì?

Tôi thậm chí không muốn đọc câu trả lời. Tôi chỉ muốn gửi điều đó để thực hiện các thay đổi trên cơ sở dữ liệu của tôi thông qua một tệp PHP.

Trả lời

281

Trong Swift 3 bạn có thể:

let url = URL(string: "http://www.thisismylink.com/postName.php")! 
var request = URLRequest(url: url) 
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 
request.httpMethod = "POST" 
let postString = "id=13&name=Jack" 
request.httpBody = postString.data(using: .utf8) 
let task = URLSession.shared.dataTask(with: request) { data, response, error in 
    guard let data = data, error == nil else {             // check for fundamental networking error 
     print("error=\(error)") 
     return 
    } 

    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {   // check for http errors 
     print("statusCode should be 200, but is \(httpStatus.statusCode)") 
     print("response = \(response)") 
    } 

    let responseString = String(data: data, encoding: .utf8) 
    print("responseString = \(responseString)") 
} 
task.resume() 

này kiểm tra cho cả lỗi mạng cơ bản cũng như các lỗi HTTP cấp cao.

Xem previous revision of this answer để hiển thị Swift 2.

+3

FYI, nếu bạn muốn thực hiện các yêu cầu thực tế (bao gồm phần trăm thoát, tạo các yêu cầu phức tạp, đơn giản hóa việc phân tích phản hồi), hãy cân nhắc sử dụng [AlamoFire] (https://github.com/Alamofire/Alamofire), từ tác giả của AFNetworking. Nhưng nếu bạn chỉ muốn thực hiện một yêu cầu 'POST' nhỏ nhặt, bạn có thể sử dụng ở trên. – Rob

+1

Cảm ơn Rob, Đó chỉ là những gì tôi đang tìm kiếm! Không có gì nhiều hơn một POST đơn giản. Câu trả lời chính xác! – angeant

+1

Sau một vài giờ tìm kiếm một số giải pháp khác nhau, dòng 3 và 4 là tiết kiệm cuộc sống của tôi như tôi không thể cho cuộc sống của tôi nhận được NSJSONSerialization.dataWithJSONObject để làm việc! – Zork

8

Heres phương pháp này tôi đã sử dụng trong thư viện khai thác gỗ của tôi: https://github.com/goktugyil/QorumLogs

Phương pháp này lấp đầy các dạng html bên trong hình thức của Google.

var url = NSURL(string: urlstring) 

    var request = NSMutableURLRequest(URL: url!) 
    request.HTTPMethod = "POST" 
    request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") 
    request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding) 
    var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true) 
+1

'ứng dụng/x-www-form-urlencoded' là gì bạn đang thiết lập? – Honey

22

Swift 3

@IBAction func submitAction(sender: AnyObject) { 

    //declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid 

    let parameters = ["id": 13, "name": "jack"] 

    //create the url with URL 
    let url = URL(string: "www.thisismylink.com/postName.php")! //change the url 

    //create the session object 
    let session = URLSession.shared 

    //now create the URLRequest object using the url object 
    var request = URLRequest(url: url) 
    request.httpMethod = "POST" //set http method as POST 

    do { 
     request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body 
    } catch let error { 
     print(error.localizedDescription) 
    } 

    request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
    request.addValue("application/json", forHTTPHeaderField: "Accept") 

    //create dataTask using the session object to send data to the server 
    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in 

     guard error == nil else { 
      return 
     } 

     guard let data = data else { 
      return 
     } 

     do { 
      //create json object from data 
      if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] { 
       print(json) 
       // handle json... 
      } 
     } catch let error { 
      print(error.localizedDescription) 
     } 
    }) 
    task.resume() 
} 
+2

Tôi nhận được lỗi sau với mã của bạn "Không thể đọc dữ liệu vì dữ liệu không đúng định dạng". – applecrusher

+0

Tôi nghĩ rằng bạn đang nhận được phản hồi trong định dạng Chuỗi bạn có thể xác minh? – suhit

+0

tôi nghĩ rằng vấn đề ở đây trong giải pháp này là bạn vượt qua các tham số như json serializing và dịch vụ web được takeing như formdata thông số –

2
@IBAction func btn_LogIn(sender: AnyObject) { 

    let request = NSMutableURLRequest(URL: NSURL(string: "http://demo.hackerkernel.com/ios_api/login.php")!) 
    request.HTTPMethod = "POST" 
    let postString = "email: [email protected] & password: testtest" 
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) 
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data, response, error in 
     guard error == nil && data != nil else{ 
      print("error") 
      return 
     } 
     if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200{ 
      print("statusCode should be 200, but is \(httpStatus.statusCode)") 
      print("response = \(response)") 
     } 
     let responseString = String(data: data!, encoding: NSUTF8StringEncoding) 
     print("responseString = \(responseString)") 
    } 
    task.resume() 
} 
0

Swift 3 giải pháp đơn giản nhất:

var components = URLComponents(string: "https://www.myAwesomeURL.com/") 
components?.queryItems = [ 
    URLQueryItem(name: "client_id", value: myClientID), 
    URLQueryItem(name: "client_secret", value: myClientSecret), 
    URLQueryItem(name: "someCode", value: myAwesomeCode), 
] 

guard let url = components?.url else { return } 
var request = URLRequest(url: url) 
request.httpMethod = "POST" 

Và có bạn đi bạn có một yêu cầu bài với urlthông số truy vấn!

+1

điều này sẽ không thêm các thông số vào url (như trong yêu cầu nhận) thay vì đặt các tham số trong nội dung bài đăng không? –

Các vấn đề liên quan