AFNetworking- post request- add simple text to bod

2019-03-20 06:47发布

问题:

How do i add a simple string (no JSON or any other format), to a post request using AFNetworking? The best i've already succeeded was concat with '='.

And this:

 NSURLRequest* request =[myServer multipartFormRequestWithMethod:@"POST" path:@"http://my.server.com" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    NSData *tmp_data = [NSString stringWithFormat:@"%@", @"my_string!"];
    [formData appendPartWithHeaders:nil body:tmp_data];
}];

Thanks in advance!

回答1:

As simple as is, This should be the answer:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://www.my.server.com"]];
[request setHTTPMethod:@"POST"];

//set headers
NSString *contentType = @"text/xml";
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
[request addValue:@"any-value" forHTTPHeaderField: @"User-Agent"];

//create the body
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[@"my_body_string!" dataUsingEncoding:NSUTF8StringEncoding]];

//post  
[request setHTTPBody:postBody];

From here, do what you want with the http request (i used with AFNetworking for sending).

Cheers!