2014-06-08 17 views
5

Tôi đang cố triển khai các yêu cầu HTTP.Thiết lập setHTTPMethod, setURL và setHTTPBody ở đâu nhanh chóng?

Đây là mục tiêu C thực hiện

  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
     [request setURL:url]; 
     [request setHTTPMethod:@"POST"]; 
     [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
     [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
     [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
     [request setHTTPBody:postData]; 

tôi bắt đầu bằng cách viết:

 let request = NSMutableURLRequest() 
     request .setValue(postLength, forHTTPHeaderField: "Content-Lenght") 
     request .setValue(application/json, forHTTPHeaderField: Accept) 

1. yêu cầu json được đem lại cho tôi một lỗi.

2.Tôi không thể chuyển đổi setURL và SetHTTPBody từ mục tiêu C sang nhanh. Tôi không thể tìm thấy tùy chọn cho các tùy chọn này.

Mọi trợ giúp sẽ được đánh giá cao. Cảm ơn bạn.

Trả lời

11

Họ đã trở thành tài sản. Hầu hết các phương thức setter với một đối số đã trở thành các thuộc tính.

Vấn đề với dòng json của bạn là bạn không có dấu ngoặc kép xung quanh "Chấp nhận".

let request = NSMutableURLRequest() 
request.url = url 
request.HTTPMethod = "POST" 
request.setValue(postLength, forHTTPHeaderField:"Content-Length") 
request.setValue("application/json", forHTTPHeaderField:"Accept") 
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type") 
request.postBody = postData 
+0

'forHTTPHeaderField' Đừng phù hợp với bất kỳ quá tải sẵn –

+0

@TomRoggero chắc chắn rằng bạn sử dụng NSMutableURLRequest, không NSURLRequest. – Apfelsaft

6

Dưới đây là làm thế nào tôi làm điều đó trong nhanh chóng:

var yêu cầu: NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL (string: url)

request.HTTPMethod = "POST"

request.setValue (postLength, forHTTPHeaderField: "Content-Length")

request.setValue ("application/json", forHTTPHeaderField: "Conte nt-Type ")

request.HTTPBody = jsonData

0
var request: NSMutableURLRequest? 
    let HTTPMethod: String = "POST" 
    var timeoutInterval: NSTimeInterval = 60 
    var HTTPShouldHandleCookies: Bool = false 

    request = NSMutableURLRequest(URL: url) 
    request!.HTTPMethod = HTTPMethod 
    request!.timeoutInterval = timeoutInterval 
    request!.HTTPShouldHandleCookies = HTTPShouldHandleCookies 


    let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy" 
    let contentType = "multipart/form-data; boundary=\(boundary)" 
    request!.setValue(contentType, forHTTPHeaderField:"Content-Type") 
    var body = NSMutableData(); 


    let tempData = NSMutableData() 
    let fileName = filenames + ".jpg" //"prueba.jpg" 
    let parameterName = "userfile" 


    let mimeType = "application/octet-stream" 

    tempData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) 
    let fileNameContentDisposition = fileName != nil ? "filename=\"\(fileName)\"" : "" 
    let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n" 
    tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!) 
    tempData.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) 
    tempData.appendData(imageData) 
    tempData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) 

    body.appendData(tempData) 

    body.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) 

    request!.setValue("\(body.length)", forHTTPHeaderField: "Content-Length") 
    request!.HTTPBody = body 



    var vl_error :NSErrorPointer = nil 
    var responseData = NSURLConnection.sendSynchronousRequest(request,returningResponse: nil, error:vl_error) 

    var results = NSString(data:responseData, encoding:NSUTF8StringEncoding) 
    println("finish \(results)") 
0
I am calling the json on login button click 

@IBAction func loginClicked(sender : AnyObject){ 

var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API. 

var session = NSURLSession.sharedSession() 

request.HTTPMethod = "POST" 

var err: NSError? 
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters. 
request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
request.addValue("application/json", forHTTPHeaderField: "Accept") 

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
var strData = NSString(data: data, encoding: NSUTF8StringEncoding) 
println("Body: \(strData)")  
var err1: NSError? 
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1) as NSDictionary 


if(err) { 
println(err!.localizedDescription) 
} 
else { 
var success = json2["success"] as? Int 
println("Succes: \(success)") 
} 
}) 

task.resume() 
} 

Here, I have made a seperate dictionary for the parameters. 

var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"] as NSDictionary 
return params 
} 
Các vấn đề liên quan