簡體   English   中英

將HTTP正文設置為AFNetworking而不是使用本機請求

[英]Set HTTP Body to AFNetworking instead of using native request

我最近一直在嘗試讓AFNetworking像本機請求一樣工作,我一直在使用AFNetworking上載POST或GET。但是它從未正確上載我的圖像。 它總是上載到損壞的服務器,在此參考資料中我已經解釋了這個問題: 使用AFNetworking將圖像上載到服務器已損壞

我嘗試將本機NSURLConnection.sendSynchronousRequest與HTTP NSURLConnection.sendSynchronousRequest一起使用,它已上傳且未損壞。 並且此代碼完全可以正常工作,但是我在AFNetworking中需要它,因為它僅支持IOS 8+,並且出於其他原因。

        let baseURL = ""
        let selectedImage = self.userImage.image
        let imageData = NSData(data: UIImageJPEGRepresentation(selectedImage!, 0.5)!)

        let request = NSMutableURLRequest()
        request.URL = NSURL(string: baseURL)
        request.HTTPMethod = "POST"
        request.addValue("image/jpeg", forHTTPHeaderField: "Content-Type")
        let body = NSMutableData(data: imageData)
        request.HTTPBody = body

 do {
            let responseData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:nil)
            let responseString = String(data: responseData, encoding: NSUTF8StringEncoding)

            print("User image successfully uploaded navigating to home services")


        } catch (let error as NSError) {
}

以下是Objective-c中的解決方案,也可以快速復制相同的過程。 如下所示,為AFHTTPRequestOperationManager創建一個對象。

 [[AFHTTPRequestOperationManager alloc] initWithBaseURL:@"www.google.com"];

現在,使用鍵值對定義NSDictionary ,這將是您的請求正文的參數。

NSDictionary *parameters = @{
                             @"paramaname": value,
                             @"paramaname":value
                        };

現在,當調用POST請求時

 [self.manager POST:@"someMethodName" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSDictionary * responseDict = (NSDictionary *)responseObject;
    NSLog(@"responseDict : %@",responseDict);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"error  : %@ code %d",error.localizedDescription,error.code);
    }
}];

這是使用AFNetworking發送帶有參數的POST請求的方法。

     NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
    [contentDictionary setValue:@"name" forKey:@"email"];
    [contentDictionary setValue:@"name" forKey:@"username"];
    [contentDictionary setValue:@"name" forKey:@"password"];
   [contentDictionary setValue:@"name" forKey:@"firstName"];
    [contentDictionary setValue:@"name" forKey:@"lastName"];

    NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:data
                                          encoding:NSUTF8StringEncoding];
NSLog(@"%@",jsonStr);

NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

AFHTTPRequestOperation *operation = [manager    HTTPRequestOperationWithRequest:request success:<block> failure:<block>];

試試這個

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM