Failed To Send Json With NSUrlconnection - iphone

i am implementing this code wich take apple in app purchase receipt from the current transaction (not listed here) i am converting it to base64 NSData object, create new NSString with the values and keys (json object) and send it trough NSUrlconnection .
when the compiler hits the init with request the app crashes after 2 seconeds...
without to get any response. this is the code.
NSData *data = [NSData dataFromBase64String:receiptStr];
NSString *jsonString = [NSString stringWithFormat:#"{\"receipt-data\":\"(%#)\",\"password\":\"(%#)\"}", data, SHARED_SECRET];
NSLog(#"%#",jsonString);
savedReceipt = jsonString;
[[NSUserDefaults standardUserDefaults]setValue:savedReceipt forKey:#"savedrecipt"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSData *requestdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; //urlData = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://sandbox.itunes.apple.com/verifyReceipt"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSString stringWithFormat:#"%#",requestdata]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
anyone have an idea what am i doing wrong?
i am also new to json so it could be also a problem there.

That's because this line in your code:
[request setHTTPBody:[NSString stringWithFormat:#"%#",requestdata]];
Is trying to setHTTPBody to some formatted NSString, when the method is actually expecting NSData.
Just use:
[request setHTTPBody: requestdata];
And see if you have better results.

Related

How to send a basic POST HTTP request with a parameter and display the json response?

I tried a lot of things but somehow not able to figure the basics of an HTTP POST request in ios. Sometimes I get a server error other times I get status code 200 but an empty response. The backend server code works and it is sending json data in response. Somehow my ios app is not able to get that response. Any help will be appreciated!
This is one of the things I tried! GetAuthorOfBook corresponds to a php server function that accepts strBookName as a POST argument and returns the name of author as a json object!
NSURL *url = [NSURL URLWithString:#"http://mysite.com/getAuthorOfBook"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *post = [NSString stringWithFormat:#"strBookName=Rework"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setValue:#"text/html" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData ];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
The responseData should have the name of the author(strAuthorName) as a json "key":"value" pair.
The responseData isn't a json object yet. First you need to serialise it and assign it to an NSDictionary, then you can parse it by key.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
Now you should be able to access authorName by either this method (if it is just a string in the json):
NSString *authorName = [json objectForKey:#"strAuthorName"];
or like this if it is a dictionary of objects (an array of objects in the json)
NSDictionary *authorName = [json objectForKey:#"strAuthorName"];

iPhone:Http POST request

I need to send some details to a server from my iphone app.I have details as separate arrays of ID,name,quantity and strings with name,address,phone & email.I need to change the NSmutable array data into this JSON format
[
{"id":"139","name":"Samosa","quantity":"332","spice":"hot"},
{"id":"149","name":"rice","quantity":"4","spice":"mild"},
.....
]
My one doubt is [request setHTTPMethod:#"POST"];
Is the above line is enough to set the POST request.
How could I add the above details into the POST request?
Use a JSON serializer. You could use SBJSON. With SBJSON, the code will be like this:
SBJsonWriter *jsonWriter = [[[SBJsonWriter alloc] init] autorelease];
NSString *jsonParams = [jsonWriter stringWithObject:<your-NSArray>];
For adding this jsonParams to POST:
NSString *postData = [jsonParams stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:postURL];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
Not enough. You need also (minimum):
NSString *your_request_string = #"the thing in JSON format";
NSData *your_data = [your_request_string dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:your_data];
Use setHTTPBody: to add post data to your HTTP request object.
Use NSJSONSerialization to serialize your array.
NSMutableArray *array = getSomeArray();
NSError *err;
NSData *json;
json = [NSJSONSerialization dataWithJSONObject:array options:0 error:&err];
if (err) {
// handle error
}
NSURL *url = getSomeURL();
NSMutableURLRequest *req;
req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:json];
// send your request

Issue in Image uploading - base64 encoding

I am passing base64 encoded image string to the server side with the HTTP PUT method.I have tried several times but getting error message as response. That error message is because null value is getting in the server side. I have checked the same, in android code and its working fine there. I am attaching my code below.
SBJSON *parser = [[SBJSON alloc] init];
NSString *url=[NSString stringWithFormat:#"The URL i am using"] ;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"XXXXX" forHTTPHeaderField:#"USER_AGENT"];
[request setHTTPMethod:#"PUT"];
NSString *input=[NSString stringWithFormat:#"abc[image]=%#",base64encodedString];
[request setHTTPBody:[input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSASCIIStringEncoding];
NSDictionary *statuses = [parser objectWithString:json_string error:nil];
[parser release];
[json_string release];
return statuses;
I am getting error message from the server side like this: "xxxxxx.jpg is not recognized by the 'identify' command."
Kindly suggest a solution.
At last i found that the content type should be changed to "multipart/form-data" from "application/x-www-form-urlencoded". Can anyone please tell me how pass Base encoded string using this way? Pls...i am behind this issue for the last 20 days...
There could be a difference in the Base64 routine. Base64 encode the same data on the server and the iPhone and compare.
Using the simulator use a network snooper such as Wireshark on the Mac to see what is really going out and the full return from the server. If you are using SSL you can use the Mac app Charles to see the data.

How to send login and password to a server using ASIHTTPRequest?

I'm pretty new to everything that deals with http and stuff like that and i know almost nothing about how http methods work so i need your advice. In my app i have to send login and password to a server and get a response. By now i'm trying to write a method (it's called STUB in English i believe) which will work in a general way without communicating to actual server. Should i use POST method in a manner similar to:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:some_server_url];
[request addPostValue:passwordString forKey:loginString];
or something else? if first how do i receive the response from the server? Could you please show me few lines of code?
You can pass login details to server using HTTP POST method like this :
-(NSDictionary*)userLogIn:(NSMutableDictionary*)inputDictionary{
SBJSON *parser = [[SBJSON alloc] init];
NSString *convertedString=[NSString stringWithFormat:#"login=%#&password=%#",username, password];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"Give the url here"]];
[request setHTTPBody:[convertedString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"XXXX" forHTTPHeaderField:#"USER_AGENT"];
[request setHTTPMethod:#"POST"];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSASCIIStringEncoding];
NSDictionary *statuses = [parser objectWithString:json_string error:nil];
[parser release];
[json_string release];
return statuses;
}
This is a sample code and you have to change according to your requirements.

sending XML file from IPhone to a server using Post Method

I am trying to send the data to server from my Iphone client. It works fine for most values but when itry to send a string like "IPhone+Cocoa" the server shows the string as "IPhone Cocoa". I have tried to google it but without success is there any why of doing it.
Here is my code
-(void)sendRequest:(NSString *)aRequest
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:kURLRequest]];
NSString *httpBody = [NSString stringWithFormat:#"%#=%#",[requestString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[aRequest stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *aData = [httpBody dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:aData];
[request setHTTPMethod:#"POST"];
self.feedURLConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
Can anyone help me?
You do this for requestString and aRequest,but not after formatting together with your addition..
Try
httpBody = [httpBody stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
before
NSData *aData = [httpBody dataUsingEncoding:NSUTF8StringEncoding];