How to POST NSData on server using MKNetworkKIt - objective-c

Currently our application is using ASIFormDataRequest to post data on server.
I was using
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:urlWeb];
[request setShouldPresentAuthenticationDialog:NO];
[request addRequestHeader:#"User-Agent" value:#"ASIHTTPRequest"];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Content-Type" value:#"text/xml; charset=utf-8"];
[request addRequestHeader:#"SOAPAction" value:#"http://something"];
[request setUsername:#"ABC"];
[request setPassword:#"XYZ"];
[request setDomain:#"LMN"];
[request appendPostData:[strSoapEnvl dataUsingEncoding:NSUTF8StringEncoding] ];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request setNumberOfTimesToRetryOnTimeout:2];
[request startAsynchronous];
BUT ASIHTTPRequest is not supporting ARC. So I have decided to use MKNetworkKIt as replacement. But I am not getting any sample code to do the same.
I have seen downloaded code from github of Mugunth Kumar but there they used NSMutableDictionary object as parameter in MKNetworkOperation.

For SOAP, you should use something like this.
[op setCustomPostDataEncodingHandler:^NSString *(NSDictionary *postDataDict) {
DDXMLDocument *doc = [[DDXMLDocument alloc] initWithXMLString:[rootElement XMLString]
options:0
error:nil];
return [doc XMLString];
} forType:#"text/xml"];
NSDictioanry is for JSON, or URL or x-plist encoding which are infact the most common encoding types.

Related

Checking data sent in http post Request

Is it possible to check the data which I have sent in HTTP POST request, by logging the request in XCode.
Here is my code:
NSString *post = [NSString stringWithFormat:#"Firstname=%#&Lastname=%#&Email=%#",firstName,lastName,emailId];
NSLog(#"%#", post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.abcde.com/xyz/login.aspx"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
**NSLog(#"%#", request );**
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
I am logging the request as shown above in Bold. But here I am able to see only my Url and not any post data.
If it is not possible to see data here where can I see the data sent in http request.
If you want just check what data are you sending then I suggest you to use this awesome tool http://www.charlesproxy.com. It's very simple and powerful.
Just run Charles and do your request via simulator.

Post XML data with ASIFormDataRequest error

NSURL *postUrl =[[NSURL alloc] initWithString:mainString];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:postUrl];
[request setResponseEncoding:NSUTF8StringEncoding];
NSString *msgLength = [NSString stringWithFormat:#"%d", [xmlString length]];
[request addRequestHeader:#"Content-Length" value:msgLength];
NSString *contentType = [NSString stringWithFormat:#"application/xml"];
[request addRequestHeader:#"Content-Type" value:contentType];
// [request addRequestHeader:#"Content-Type" value:#"application/json"];//Test For JSON is good
[request appendPostData:theData];
[request buildPostBody];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request startAsynchronous];
[request setTimeOutSeconds:20];// 测试连接的时间,默认10s
[postUrl release];
I get Nothing from the following code, which also does not produce an error.
(void)requestFinished:(ASIHTTPRequest *)request{
NSData *theData = [request responseData];
NSString *ret = [request responseString];
NSLog(#"ret--------------%#",ret);
}
When I use JSON, I get the result.

Objective-C Asynchronous NSURLConnection to Ruby Server

I am having trouble sending asynchronous NSURLRequests to a Ruby server. When I use the following, a connection is never made:
self.data = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://domain.com/app/create_account.json"]];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request addValue:#"form-data" forHTTPHeaderField:#"Content-Disposition"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
However, when I exchange the last line with:
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
Everything works great. But I do need to make this connection asynchronously...
EDIT-Working Example
NSURL *url = [NSURL URLWithString:#"http://domain.com/app/create_account.json"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:data forKey:#"data"];
[request setDelegate:self];
[request startAsynchronous];
It seems RESTful services need their own third party framework in this case.
you can try following using restkit api
- (void)sendAsJSON:(NSDictionary*)dictionary {
RKClient *client = [RKClient clientWithBaseURL:#"http://restkit.org"];
// create a JSON string from your NSDictionary
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
NSError *error = nil;
NSString *json = [parser stringFromObject:dictionary error:&error];
// send your data
if (!error)
[[RKClient sharedClient] post:#"/some/path" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self];
}
referance:
https://github.com/RestKit/RestKit/wiki/Tutorial-%3A-Introduction-to-RestKit
https://github.com/RestKit/RestKit/wiki/Posting-NSDictionary-as-JSON
Thanks
Nikhil

Post data in Objective C using Json

I am trying to post data to a PHP web service.
I am familiar doing this in html using query $.post but I am very much stumped trying this in objective C.
I tried several blogs & questions found on stackoverflow.
I finally came up with the following code:
NSString *jsonRequest = [NSString stringWithFormat:#"{\"Email\":\"%#\",\"FirstName\":\"%#\"}",user,fname];
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http:myurl..."];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
I also tried:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
My web service creates a new user on post and returns the userID.
Both successfully make the web service call(a new userID is created), however they do not post the data, i.e. a blank user is created every time.
Please tell me if I am missing anything.
Thanks.
My other attempts:
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:#"myUrl.. "]];
[request setHTTPMethod:#"POST"];
NSString *postString = #"Email=me#test.com&FirstName=Test";
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc]
initWithRequest:request delegate:self];
I finally solved the issue:
FInally, figured out what was wrong. I was using http://mypath?params=123 as my url. I did not gig the complete url(never needed it in other languages). But here I needed to give htt://mypath/index.php?params=123
I think you would be better off using the NSJSONSerialization class like this:
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
email, #"Email",
fname, #"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];
Using a dictionary and then converting it to JSON it's easier than creating it like a string.
Good luck!
[SWIFT 3.0] (update)
let tmp = ["email": email,
"FirstName": fname]
let postData = try? JSONSerialization.data(withJSONObject: tmp, options: .prettyPrinted)
request.httpBody = postData
I have run your code, and server side receive all message.
POST / HTTP/1.1
Host: linux-test
User-Agent: demoTest/1.0 CFNetwork/548.1.4 Darwin/11.3.0
Content-Length: 44
Accept: application/json
Content-Type: application/json
Accept-Language: en
Accept-Encoding: gzip, deflate
Connection: keep-alive
{"Email":"test#test.com","FirstName":"test"}
And follow code, if jsonRequest has Non-ASCII characters, the [jsonRequest length] will be wrong.
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
You can use strlen instead.
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:strlen([jsonRequest UTF8String])];
or
[jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
Try this one
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#posts", SeverURL]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"content-type" value:#"application/json"];
[request addRequestHeader:#"User-Agent" value:#"iOS"];
request.allowCompressedResponse = NO;
request.useCookiePersistence = NO;
request.shouldCompressRequestBody = NO;
request.delegate=self;
NSString *json=[[self prepareData] JSONRepresentation];//SBJSON lib, convert a dict to json string
[request appendPostData:[NSMutableData dataWithData:[json dataUsingEncoding:NSUTF8StringEncoding]]];
[request startSynchronous];

POST to server results in GET request

I'm trying to do a simple POST request to a server, with this code:
NSString *post = [[NSString alloc] initWithFormat:#"email=%#&password=%#", self.email.text, ..]; // .. simplified keychainItem
NSData *postEncoded = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postEncoded length]];
NSURL *url = [NSURL URLWithString:#"http://eng.studev.groept.be/web2.0/a11_web02/testApp.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postEncoded];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
When debugging on the server, this actually results in a GET request. That explains why I'm getting a PHP error when trying to read $_POST[ ] variables. Bottom line: why isn't the setHTTPMethod: being accepted?
(extra information: when just coding in PHP on the server, use of POST works normally)