AFNetworking- post request- add simple text to body

主宰稳场 提交于 2019-12-04 11:41:23

问题


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!



来源:https://stackoverflow.com/questions/17505707/afnetworking-post-request-add-simple-text-to-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!