How to set JSON NSData with ASIFormDataReuest - iphone

Hi I want to pass my userName and Password to WCF Webservice from iPhone. I'm using ASIFormDataRequest.
Here is my code
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:txtUsername forKey:#"userName"];
[request setPostValue:txtPassword forKey:#"password"];
[request setDelegate:self];
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
[request startAsynchronous];
How do I pass JSON Data?
I could use this...
[request appendPostBody:jsonData]; // JSON as NSData
but how do I set JSON to NSData?
NSData *jsonData = #"{'userName':'john', 'password':'secret'}";
Please help me!

Supposing you want to encode the JSON in UTF-8 as stated in your header:
NSString *json = #"{'userName':'john', 'password':'secret'}";
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
[request appendPostBody:jsonData];

Related

How to post xml data in url as request?

I am developing an application in which i want to post
xml data as request but i am not able to post it correctly ,i think.
My request xml data is
<loginRequest><username>101</username></loginRequest>
and my request is as follows :
`NSString *post=#"<loginRequest><username>101</username></loginRequest>";
NSURL *url = [NSURL URLWithString:#"my url"];
__block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
NSMutableData *mutData=[[NSMutableData alloc]init];
[request addRequestHeader:#"Content-Type" value:#"text/xml"];
[request setPostValue:#"test" forKey:#"body"];
[request setCompletionBlock:^{
NSData *data=[request responseData];
NSString *response=[request responseString];
}];
[request setFailedBlock:^{
NSLog(#"Failed");
}];
[request startAsynchronous];
`
Kindly help me with this..
You can check with your server api whether it supports different response type..
Accordingly you can set "Accept" parameter of HTTP request header.
[request addRequestHeader:#"Accept" value:#"application/xml"];

Post Data but GET Method json -ios

how can i use the get method to post data on an api link with 6 values and a json format?
im really fuzzled. im doing this for days . is it best to have 6 textfields that will be used to write the value and a button to indicate post data?
check out my code and please help.
-(IBAction)postDataPressed
{
NSString *urlString = #"http://192.168.18.8/apisample2/friendb.php?fm=jsn";
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:user.text forKey:#"un"];
[request setPostValue:pass.text forKey:#"pd"];
[request setPostValue:gender.text forKey:#"gd"];
[request setPostValue:age.text forKey:#"ag"];
[request setPostValue:status.text forKey:#"st"];
[request setPostValue:lookfor.text forKey:#"lf"];
[request setRequestMethod:#"GET"];
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
NSLog(#"Response: %#", responseString);
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(#"Error: %#", error.localizedDescription);
}];
[request setDidFinishSelector:#selector(requestFinished:)];
[request setDidFailSelector:#selector(requestFailed:)];
[request startAsynchronous];
}
i hope someone will help.
NSString *request_url = [NSString stringWithFormat: #"http://192.168.18.8/apisample2/friendb.php?fm=jsn&un=%#&pd=%#&gd=%#&ag=%#&st=%#&lf=%#",
user.text, pass.text, gender.text, age.text,status.text,lookfor.text];
NSURL *url = [NSURL URLWithString:request_url];
ASIHttpRequest *request = [ASIHttpRequest requestWithURL:url];
request.delegate = self;
....
HTTP Get method only accept data in url, called query string, so you have to build query string yourself.

Upload video taken with iphone camera with PUT method

How can i upload a video taken with the camera or contained in the phone memory?
I need to upload it using a PUT method.
Thank you
Code for photo uploading:
- (void)uploadPhoto:(NSData *)data
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"PUT"];
[request addRequestHeader:#"Date" value:timeStamp];
[request addRequestHeader:#"Auth" value:signature];
[request addRequestHeader:#"Client" value:apiClient];
[request addRequestHeader:#"Accept" value:apiAccept];
[request addRequestHeader:#"USER" value:userHeader];
[request appendPostData:data];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSLog(#"%#",responseString);
// Use when fetching binary data
NSData *responseData = [request responseData];
NSLog(#"%#",responseData);
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog(#"%#",error);
}
none of the 3 methods at the end are called after i make this request.
Please help me.
Regards,
response string:
|?xml version="1.0" encoding="UTF-8"?|
|error|
|code|InvalidParameter|/code|
|message|Invalid parameter specified (user)|/message|
|/error|
You can do it using ASIHTTPRequest. Here is a sample:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request appendPostData:myVideoData];
[request setRequestMethod:#"PUT"];

ASIHTTPRequest wrapping JSON in quotes

I'm using ASIHTTPRequest and json-framework to post JSON to a rails app,
The problem is that when the JSON arrives on the server it is wrapped in double quotes,
Here is the code i am using to encode and send the JSON:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/shared_lists.json",kAPIRoot]]];
NSString *dataString = [NSString stringWithFormat:#"shared_items=%#&shared_list=%#&facebook_id=%#",[sharedItems JSONRepresentation],[sharedList JSONRepresentation],facebookID];
NSLog(#"%#",[NSString stringWithUTF8String:[[dataString dataUsingEncoding:NSUTF8StringEncoding] bytes]]);
[request appendPostData:[dataString dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestDone:)];
[request setDidFailSelector:#selector(requestWentWrong:)];
[queue addOperation:request];
Which logs correctly as:
shared_items=[{"entity_id":"531","position":"1"},{"entity_id":"733","position":"2"},{"entity_id":"723","position":"3"},{"entity_id":"2530","position":"4"}]&shared_list={"list_id":1197}&facebook_id=-1540981104
Although when it arrives on the server it outputs as:
shared_items="[{"entity_id":"531","position":"1"},{"entity_id":"733","position":"2"},{"entity_id":"723","position":"3"},{"entity_id":"2530","position":"4"}]",shared_list="{"list_id":1197}",facebook_id="-1540981104"
How do i stop the arrays being wrapped up as a single string?
Try this way:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/shared_lists.json",kAPIRoot]]];
NSString *dataString = [NSString stringWithFormat:#"shared_items=%#&shared_list=%#&facebook_id=%#",[sharedItems JSONRepresentation],[sharedList JSONRepresentation],facebookID];
NSMutableData *requestBody = [[NSMutableData alloc] initWithData:[dataString dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[request setPostBody:requestBody];
[request addRequestHeader:#"Content-Type" value:#"application/json; encoding=utf-8"];
[request setUseSessionPersistence:NO];
[request setUseCookiePersistence:NO];
[request setCacheStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy];
I solved the problem by manually creating the JSON String like so:
NSString *dataString = [NSString stringWithFormat:#"{\"shared_items\":%#,\"shared_list\":%#,\"facebook_id\":%#}",[sharedItems JSONRepresentation],[sharedList JSONRepresentation],facebookID];

upload image to server

i want to upload an
UIImage
to a server.
the problem i dont know how to add it to my post to the server.
until now i sent post with thia:
NSString *reqURL = [NSString stringWithFormat:#"url"];
reqURL = [reqURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:reqURL]];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &err];
there is any different way to do for image?
Use ASIHttpRequest
-(void)uploadImage{
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
// Upload a file on disk
[request setFile:#"/Users/ben/Desktop/ben.jpg" withFileName:#"myphoto.jpg" andContentType:#"image/jpeg"
forKey:#"photo"];
// Upload an NSData instance
[request setData:UIImageJPEGRepresentation(myUIImage) withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"photo"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(uploadRequestFinished:)];
[request setDidFailSelector:#selector(uploadRequestFailed:)];
[request startAsynchronous];
}
This answer points to this wrapper framework that should make it easy to do what you want without dealing with HTTP header strings and so on.
Basically, you'll turn your UIImage into an NSData object using a function like UIImagePNGRepresentation() and then upload it over HTTP.