Send data via POST with afnetworking
By sub-non-fish · May 26, 2014
Afnetworking sending JSON data in a POST request is a bit special.
Afnetworking version is 2.0.2
There are two forms of post-send data:
1. Send Plain text content
2, the body part of the Sent with files (pictures, audio or other binary data)
The corresponding content-type have two kinds:
1, application/x-www-form-urlencoded
2, Multipart/form-data
The traditional use of post to send data for uploading files, Afnetworking provides a direct interface:
[Self.manager Post:post_url Parameters:params
constructingbodywithblock:^ (id< Afmultipartformdata> FormData) {
Append binary data directly to FormData as key value
[FormData Appendpartwithformdata:[str datausingencoding:nsutf8stringencoding]
name:@ "Key1"];
[FormData appendpartwithfiledata:imgdata name:@ "ImageFile"
filename:@ "Img.jpg" mimetype:@ "Image/jpeg"];
}
success:^ (afhttprequestoperation *operation, id responseobject) {
Post-Success Processing
}
failure:^ (afhttprequestoperation *operation, Nserror *error) {
Post-failure processing
}];
Send plain text content using POST:
-(Nsmutableurlrequest *) Postrequestwithurl: (nsstring *) URL content: (NSString *) text
{
Nsmutableurlrequest *request =
[[Nsmutableurlrequest alloc] initwithurl:url];
[Request sethttpmethod:@ "POST"];
[Request setvalue:@ "application/x-www-form-urlencoded"
forhttpheaderfield:@ "Contsetent-type"];
[Request Sethttpbody:1];
return request;
}
Nsoperation *operation =
[Self.manager Httprequestoperationwithrequest:request
success:^ (afhttprequestoperation *operation, id responseobject) {
Post-Success Processing
}
failure:^ (afhttprequestoperation *operation, Nserror *error) {
Post-failure processing
}];
[Self.manager.operationQueue addoperation:operation];
Where Self.manager is the Afhttprequestoperationmanager instance.
_manager = [[Afhttprequestoperationmanager alloc] initwithbaseurl:url];
For Web sites that successfully return JSON-formatted data but are displayed in the failure callback,
The content type is not set to Text/json because the server returns data in the Web page
For our company the server returns the content type text/html so I set it as follows,
For different situations you can set the appropriate accepted content type types according to your own situation
_manager.responseserializer.acceptablecontenttypes = [Nsset setwithobject:@ "text/html"];
Send data via POST with afnetworking