14

我正在尝试使用AFNetworking在 CouchDB 服务器中创建附件来发出 HTTP PUT 请求。服务器需要在 HTTP 正文中使用 base64 编码的字符串。如何在不使用键/值对发送 HTTP 正文的情况下发出此请求AFNetworking

我开始研究这个方法:

- (void)putPath:(NSString *)path
 parameters:(NSDictionary *)parameters
    success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
    failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

但是这里的参数是类型:NSDictionary. 我只想在 HTTP 正文中发送一个 base64 编码的字符串,但不与密钥关联。有人可以指出我使用的适当方法吗?谢谢!

4

6 回答 6

11

Hejazi 的答案很简单,应该很好用。

如果由于某种原因,您需要对一个请求非常具体——例如,如果您需要覆盖标头等——您也可以考虑构建自己的 NSURLRequest。

这是一些(未经测试的)示例代码:

// Make a request...
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL];

// Generate an NSData from your NSString (see below for link to more info)
NSData *postBody = [NSData base64DataFromString:yourBase64EncodedString];

// Add Content-Length header if your server needs it
unsigned long long postLength = postBody.length;
NSString *contentLength = [NSString stringWithFormat:@"%llu", postLength];
[request addValue:contentLength forHTTPHeaderField:@"Content-Length"];

// This should all look familiar...
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postBody];

AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:success failure:failure];
[client enqueueHTTPRequestOperation:operation];

NSData 类别方法base64DataFromString此处可用

于 2013-06-18T11:36:01.090 回答
4

您可以使用multipartFormRequestWithMethod以下方法:

NSURLRequest *request = [self multipartFormRequestWithMethod:@"PUT" path:path parameters:parameters constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
    [formData appendString:<yourBase64EncodedString>]
}];
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:success failure:failure];
[client enqueueHTTPRequestOperation:operation];
于 2013-06-18T08:23:22.720 回答
4

这里有一个发送原始 json的示例:

NSDictionary *dict = ...
NSError *error;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:&error];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:YOUR_URL parameters:nil error:nil];

req.timeoutInterval = 30;
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setValue:IF_NEEDED forHTTPHeaderField:@"Authorization"];

[req setHTTPBody:dataFromDict];

[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
    if (!error) {
        NSLog(@"%@", responseObject);
    } else {
        NSLog(@"Error: %@, %@, %@", error, response, responseObject);
    }
}] resume];
于 2016-10-07T01:31:57.100 回答
1
 NSData *data = someData;
 NSMutableURLRequest *requeust = [NSMutableURLRequest requestWithURL:          
 [NSURL URLWithString:[self getURLWith:urlService]]];

[reqeust setHTTPMethod:@"PUT"];
[reqeust setHTTPBody:data];
[reqeust setValue:@"application/raw" forHTTPHeaderField:@"Content-Type"];

NSURLSessionDataTask *task = [manager uploadTaskWithRequest:requeust fromData:nil progress:^(NSProgress * _Nonnull uploadProgress) {

} completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

}];
[task resume];
于 2016-11-25T14:08:23.390 回答
0

我正在使用 AFNetworking 2.5.3 并为 AFHTTPRequestOperationManager 创建新的 POST 方法。

extension AFHTTPRequestOperationManager {

    func POST(URLString: String!, rawBody: NSData!, success: ((AFHTTPRequestOperation!, AnyObject!) -> Void)!, failure: ((AFHTTPRequestOperation!, NSError!) -> Void)!) {

        let request = NSMutableURLRequest(URL: NSURL(string: URLString, relativeToURL: baseURL)!)
        request.HTTPMethod = "POST"
        request.HTTPBody = rawBody

        let operation = HTTPRequestOperationWithRequest(request, success: success, failure: failure)

        operationQueue.addOperation(operation)
    }

}
于 2015-05-13T03:51:43.487 回答
0

请使用以下方法。

+(void)callPostWithRawData:(NSDictionary *)dict withURL:(NSString 
*)strUrl withToken:(NSString *)strToken withBlock:(dictionary)block
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
Please use below method.
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@/%@",WebserviceUrl,strUrl] parameters:nil error:nil];

req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[req setValue:strToken forHTTPHeaderField:@"Authorization"];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
    if (!error) {
        if ([responseObject isKindOfClass:[NSData class]]) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
            if ((long)[httpResponse statusCode]==201) {
                NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
                [dict setObject:@"201" forKey:@"Code"];

                if ([httpResponse respondsToSelector:@selector(allHeaderFields)]) {
                    NSDictionary *dictionary = [httpResponse allHeaderFields];
                    NSLog(@"%@",[dictionary objectForKey:@"Location"]);
                     [dict setObject:[NSString stringWithFormat:@"%@",[dictionary objectForKey:@"Location"]] forKey:@"Id"];
                     block(dict);
                }
            }
            else if ((long)[httpResponse statusCode]==200) {
                //Leave Hours Calculate
                NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
                block(serializedData);
            }
            else{
            }
        }
        else if ([responseObject isKindOfClass:[NSDictionary class]]) {
            block(responseObject);
        }
    } else {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setObject:ServerResponceError forKey:@"error"];
        block(dict);
    }
}] resume];
}
于 2017-10-03T12:31:22.903 回答