swift2 使用Alamofire设置HTTP头和HTTP正文

9rygscc1  于 2022-11-06  发布在  Swift
关注(0)|答案(1)|浏览(202)

我一直在使用NSURLConnection进行请求,我想将代码迁移到Alamofire。
这是我的NSURLConnection代码。

var requestString: NSString = "http://api.domainname.com/api/v1/auth/register";
var url: NSURL = NSURL(string: requestString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!;

var urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: url);
urlRequest.setValue("\(base64LoginString)", forHTTPHeaderField: "Authorization");
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type");
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept");

var httpBodyDictionary: NSMutableDictionary = NSMutableDictionary();
httpBodyDictionary.setObject(self.emailTextField.text, forKey: "email");
httpBodyDictionary.setObject(self.usernameTextField.text, forKey: "username");
httpBodyDictionary.setObject(self.passwordTextField.text, forKey: "password");

urlRequest.HTTPMethod = "POST";

NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    if(data != nil) {
          //PROCESS DATA
    }
});

不过,我试过Alamofire,但我不能使它工作。

火焰之火

var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
defaultHeaders["Authorization"] = "\(base64LoginString))"
defaultHeaders["Content-Type"] = "application/json)"
defaultHeaders["Accept"] = "application/json)"

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders;

let manager = Alamofire.Manager(configuration: configuration)

var requestString: NSString = "http://api.domainname.com/api/v1/auth/register";
var url: NSURL = NSURL(string: requestString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!;

var urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: url);
urlRequest.HTTPMethod = Alamofire.Method.POST.rawValue;

let parameters = ["email": self.emailTextField.text,
        "username": self.usernameTextField.text,
        "password": self.passwordTextField.text]

do {
        urlRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
} catch {
    // No-op
}

Alamofire.request(urlRequest).responseJSON(completionHandler: { (urlRequest, urlResponse, result) -> Void in
        print(urlResponse);        
    //print(result);
})

有没有人能指出正确的方向?我花了一整天的时间试图让它工作。
注意:使用Swift 2/ XCode 7测试版6

UPDATE尝试了Rob的建议,但我得到了返回,当我使用NSURLConnection时不会发生这种情况
打印的响应

Optional(<NSHTTPURLResponse: 0x7fdbc222a2b0> { URL: http://api.domainname.com/api/v1/auth/register } { status code: 422, headers {
    "Cache-Control" = "no-cache, proxy-revalidate";
    Connection = "Keep-Alive";
    "Content-Type" = "application/json";
    Date = "Thu, 10 Sep 2015 14:35:13 GMT";
    Server = "nginx/1.8.0";
    "Set-Cookie" = "laravel_session=eyJpdiI6InZjSVwvcVd3NjR6SitZSlZNMGdXdElRPT0iLCJ2YWx1ZSI6IjJBeXdWTHRlRUNQa2RTSFBDYlU0bWlBRkF3c0pzcEx2YzQxdXk0ZnlxZ2xERUkrWmFZNlNISUlyZmpnWjZkamdxVFJXaGxOQmFtVlZZWElWdnFYdlBRPT0iLCJtYWMiOiI5MWY2NjU4ODViYjhlYWM4N2YwOTg2ZTA2OWYzNmU1MmE3ZWEzN2E5ZTA5ZjA5YjMyYmExN2FmMzFhZjRiMmJhIn0%3D; expires=Thu, 10-Sep-2015 16:35:13 GMT; Max-Age=7200; path=/; httponly";
    "Transfer-Encoding" = Identity;
} })
l7mqbcuq

l7mqbcuq1#

你不需要设置Content-TypeAccept,也不需要设置请求主体,也不需要自己使用NSJSONSerialization,Alamofire让你摆脱了构建请求的麻烦,所以你可以这样做:

let requestString = "http://api.domainname.com/api/v1/auth/register"

let parameters = [
    "email"    : emailTextField.text!,
    "username" : usernameTextField.text!,
    "password" : passwordTextField.text!
]

let headers = ["Authorization": base64LoginString]

Alamofire.request(.POST, requestString, parameters: parameters, encoding: .JSON, headers: headers).responseJSON { request, response, result in
    print(response)
}

或者,如果您不想自己构建base64LoginString,您也可以执行以下操作:

Alamofire.request(.POST, requestString, parameters: parameters, encoding: .JSON)
    .authenticate(user: user, password: password)
    .responseJSON { request, response, result in
        print(response)
}

如果仍然不起作用,我建议(a)编辑你的问题,分享准确的错误信息;(B)在Charles之类的工具中观察旧代码和新代码,并确定这两个请求之间的差异有多大。

相关问题