Post Data format is diffrent then what I needed - iphone

I am having a simple problem while making a request to server for updating a name field. I need to post some data in this format:-
{"api_token"=>"api", "device_token"=>"device", "user"=>{"name"=>"mohit"}, "id"=>"4"}
But when i am trying to post something its posting in this format:-
{"user"=>"(\n {\n name = ChangeName;\n }\n)", "api_token"=>"api", "device_token"=>"device", "id"=>"4"}
I am not able to figure out how to change my code to generate proper request. Here is the code that I am using.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://localhost:3000/users/4?api_token=api&device_token=device"]];
NSMutableDictionary *dict= [NSMutableDictionary dictionaryWithObjectsAndKeys: #"Mike",#"name", nil];
NSArray *array=[[NSArray alloc]initWithObjects:dict, nil];
[request setPostValue:array forKey:#"user"];
[request setRequestMethod:#"PUT"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestFinished:)];
[request startAsynchronous];
Please let me know if i need to post some more code fragments.

ASIFormDatRequest setPostValue:forKey: wants strings, not structures. It ends up calling description to convert them to strings and you're getting the printable description of an array with a dictionary in it.
Rails uses a naming scheme that allows you to simulate a hierarchy in a flat space using a field naming convention detailed at http://guides.rubyonrails.org/form_helpers.html. You should read that and understand the html produced by the form helpers.
Try:
[request setPostValue:#"mohit" forKey:#"user[name]"];
and rails will unpack it into the proper kind of collection on the server.

Related

How to submit a very-very long String to server via POST and get jSON response

I wish to send a very very long string(length of string is more than 10000) to the server and in return get the jSON response from the string.What is the best approach for the task. I am sending various parameters along with this very very long string.
Split down your long string to parts which can be send over one request. Create a json like this
{
"index":"0",
"length":"LENGTH_OF_STRING",
"string":"xsfsffwff.......",
//other json parameters
}
then you can send your string
The problem is that you're trying to put this all into a query parameter. Most servers have built-in limits for URLs, and for good reason.
There's nothing special about the body of an HTTP POST, so just send that up like you would anything else. Just make sure that you set the Content-Length header (since you know that; it might be covered by the HTTP library) and then just stream your data up. No need for any encoding or query params.
I don't know much about objective-c, but I'm sure there's a way to send data like this in an HTTP POST very simply. I've done this with Go and node.js, and both have simple ways of sending arbitrary data in a POST request body.
If you are using the ASI-Http classes , then you can send request like this
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:[WebService getAddPhoto]]];
[request addPostValue:[[imgArray objectAtIndex:i] valueForKey:#"vComments"] forKey:#"comment"];
NSData *imageData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:[[imgArray objectAtIndex:i] valueForKey:#"vPhoto"]]);
NSString *encodedString = [imageData base64EncodingWithLineLength:[imageData length]];
[request addPostValue:encodedString forKey:#"Photo"];
[request setDelegate:self];
[request startAsynchronous]

ASIHTTPRequest Send Data With Each Request

I have an array which includes URLs of JSON feeds. I am using ASIHTTPRequest to download the feed and process it. Each feed contains several JSON entries or objects. The request downloads the data and selects only one object and stores it.
The feeds URLs look like this: http:www.*.com/id.json, where id is some string. After downloading the data and selecting the object, I'd like to store the id in a dictionary as a key that maps to a value of the object downloaded.
How can I pass that string with the request? So for example:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
request.tag = 3;
[request setDelegate:self];
[request startAsynchronous];
Now in requestFinished, I can identify that request as follows: if (request.tag == 3. Along with tag of 3, I'd like to send the ID. So I can do something with it in if (request.tag == 3). Is there some property where I can pass a string or any data along with a request?
You can pass your own dictionary of data in the userInfo property, which, like the tag property, can be read back on the request after receiving the response.
NSString* jsonId = #"1234";
request.userInfo = [NSDictionary dictionaryWithObject:jsonId forKey:#"id"];
See documentation.
If you need to handle success and failure on many different types of
request, you have several options:
If your requests are all of the same broad type, but you want to
distinguish between them, you can set the userInfo NSDictionary
property of each request with your own custom data that you can read
in your finished / failed delegate methods. For simpler cases, you can
set the request’s tag property instead. Both of these properties are
for your own use, and are not sent to the server.
If you need to handle success and failure in a completely
different way for each request, set a different setDidFinishSelector /
setDidFailSelector for each request
If you want to post data like a web page posts a form, you can use the ASIFormDataRequest subclass. It makes it very easy to send POST requests with strings you add individually:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"Ben" forKey:#"first_name"];
[request setPostValue:#"Copsey" forKey:#"last_name"];
See the documentation.

Sending multiple arguments to Drupal REST Services from iPhone

I am trying to access a Drupal service that takes more than one argument. The method is views.get and the server I'm using is REST 6.x-2.0-beta3. I am retrieving data from the server for 0 or 1 arguments with no trouble. Any argument after the first, however, is simply ignored. I have tested the view on the Drupal site, and it limits results correctly for every argument passed.
I've come to the conclusion that my problem must be the formatting, but I've tried nearly everything I can think of, not to mention a dozen suggestions I've found while Googling for an answer. My code is below:
responseData = [[NSMutableData data] retain];
NSMutableString *httpBodyString =[[NSMutableString alloc] initWithString:#"method=views.get&view_name=apps&args=1&display_id=default"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://drupalserver.com/services/rest/service_views/get.json"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[httpBodyString dataUsingEncoding:NSUTF8StringEncoding]];
[httpBodyString release];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
I have tried:
args=1,2
args=[1,2]
args="1,2"
args=["1","2"]
and several others along that vein. Does anyone know the proper way to do this?
You should considering using, https://github.com/workhabitinc/drupal-ios-sdk

Empty body in POST in ASIHTTPRequest

Basically, I am sending a POST request with an empty data body:
ASIHTTPRequest *request [ASIHTTPRequest alloc] init];
[request setURL:[NSURL URLWithString:escapedUrlString]];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Content-Type" value:#"application/xml"];
[request startSynchronous];
But i am getting this response each time:
Incorrect NSStringEncoding value 0x0000 detected. Assuming NSStringEncodingASCII. Will stop this compatiblity mapping behavior in the near future.
I am wondering if it's mandatory to set post values.
I don't have much experience with the ASIHTTPRequest wrapper but I can see you are initialising it with alloc:init whilst most examples I've seen have a convenience initialiser requestWithURL:(NSURL*)url i.e.
ASIHTTPRequest *request = [AIHTTPRequest requestWithURL:escapedUrlString];
At a guess I'd say this convenience initaliser will also set some of the required variables for your post request to work, including NSStringEnconding.
From the ASIHTTPRequest documentation at http://allseeing-i.com/ASIHTTPRequest/How-to-use#handling_text_encodings
Handling text encodings
ASIHTTPRequest will attempt to read
the text encoding of the received data
from the Content-Type header. If it
finds a text encoding, it will set
responseEncoding to the appropriate
NSStringEncoding. If it does not find
a text encoding in the header, it will
use the value of
defaultResponseEncoding (this defaults
to NSISOLatin1StringEncoding).
When you call [request
responseString], ASIHTTPRequest will
attempt to create a string from the
data it received, using
responseEncoding as the source
encoding.
As Rog says, use initWithURL or requestWithURL. Anyway, in my case the problem was that I was connecting to a slow server and the request timed out giving the "Incorrect NSStringEncoding value 0x0000 detected" error.
I solved it with:
request.timeOutSeconds = 50;
You can try with more than 50 second if your server is even slower.

I need the correct syntax for the setValue:forHTTPHeaderField: method on NSMutableURLRequest

I am pulling my hair out trying to conjure up the correct syntax to set the HTTP header information do a byte-range load from an HTTP server.
This is the offending method on NSMutableURLRequest
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field
This is how I am using this method to load the first 512 byte of a URL request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"0-512\r\n" forHTTPHeaderField:#"Range"];
So far it is ignored and I always receive the entire data payload. I just want the range of bytes specified (0 - 512). Can someone please relieve my headache?
Update:
I have used curl to confirm that my web server supports byte ranges thusly:
curl --range 0-2047 http://www.somewhere.com/humungodata.dat -o "foobar"
The file size of foobar is 2048
Cheers,
Doug
Problem solved.
By adding additional header fields the code immediately worked correctly. Why? Dunno. But it works:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"keep-live" forHTTPHeaderField:#"Connection"];
[request setValue:#"300" forHTTPHeaderField:#"Keep-Alive"];
[request setValue:#"bytes=0-2047" forHTTPHeaderField:#"Range"];
Your original code was wrong in the setValue line, it should be #"bytes=0-512". In your followup, you used the correct string, so the other headers should not be needed.
What you have there should be the correct way to add a header value to a URL request, however i thought only posts got header values, maybe im wrong, have you tried doing this on other enviroments and gotten it to work? Maybe take out the \r\n?