I have setPostValue in ASIFormDataRequest. like so:
ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setPostValue:#"helmi" forKey:#"username"];
[request setPostValue:#"123" forKey:#"password"];
[request setPostValue:#"goods" forKey:#"purchase"];
NSLog(#"...");
I'd like to show the NSLog of Post Value before send to server. reasons is because I have many variable value in post value, need to check whether I put correctly.
ASIFormDataRequest holds a variable called postData which is an NSMutableArray. You can access its value using
NSLog(#"%#", [request valueForKey#"postData"])
Related
I want to send a new object created on iOS to a receiving server with a POST method using JSON data type. From what I know about receiving data from the server in iOS, is that all JSON handling was simplified by Apple with the introduction of iOS 8. But in contradistinction to GETting JSON objects, POSTing those isn't really described anywhere I could find ...
The first steps I took to try and solve the problem looked as follows:
How can I send the below format to server???
{"createFrom":"","createType":"","filename":"AC","filter":"","lstData":[{"FieldName":"LNK_RELATED_CN","FieldValue":""},{"FieldName":"LNK_RELATED_CO","FieldValue":""},{"FieldName":"MLS_PURPOSE","FieldValue":"Inquiry"},{"FieldName":"MLS_STATUS","FieldValue":"Open"},{"FieldName":"MMO_NOTES","FieldValue":""},{"FieldName":"DTE_NEXTACTIONDATE","FieldValue":""},{"FieldName":"MMO_NEXTACTION","FieldValue":""}],"password":"Infodat2","username":"manmeets","IsNew":true}
I have seen code like this:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:#"%#AssetSave",[defaults objectForKey:#"siteAddress"]]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
_responseData = [NSMutableData data];
NSLog(#"request : %#", request);
_nsurlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
But I really don't know how to send a JSON object to a server using a POST method at all. Could anybody please help me out?
The code you have is fine, you just need to create jsonData:
jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
(thought you should really also include an &error so you can see what's happening if something goes wrong)
i'm developing an app for iPhone and I'm stuck in one call, I have to send data via POST, the django web programmer tells me the app has to receive
param_one = request.POST['param_one']
param_two = request.POST['param_two']
but I cannot make it to send any data...
I'm learning objective-c, so please, could you tell me how to do it with an example?
PS: all the other calls that doesn't send any data, or pass data through url (GET method) works fine, so I'm making the connection correctly
Here's the code I'm using:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:#"somename" forKey:#"user"];
NSString *jsonString = [dict JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest * Â request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://web.com/custom/url/call/"]];
[request setValue:jsonString forHTTPHeaderField:#"json"];
[request setHTTPMethod:#"POST"];
[request addValue:csrf forHTTPHeaderField:#"X-CSRFToken"];
[request setHTTPBody:jsonData];
senddata = [[NSURLConnection alloc] initWithRequest:request delegate:self];
You should probably add:
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
Then the server will know that what you're sending is UTF-8 encoded JSON and it will be able to parse it appropriately. Otherwise it just gets a formless blob of data.
Unless it's for debugging purposes, it's very odd that you put the JSON string into both the header and the body.
I've sent this URL via post:
https://api.instagram.com/v1/users/XXX/relationship?action=unfollow&access_token=YYY
XXX is a valid userid, I've checked that multiple times. The token (YYY) is correct too.
This is the response:
{"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"please supply action=approve,ignore,follow,block,unblock,unfollow"}}
I've tried action=follow and action=unfollow. Is it possible, that this is a bug? Where can I report it?
Instagram API Documentation: http://instagram.com/developer/endpoints/relationships/
The problem is that you are not sending the action as postdata. I had the exact problem just yesterday.
The access_token should be sent in the url, but the action=follow should be in the postdata of the request!
NSString *initialURL = [NSString stringWithFormat:#"https://api.instagram.com/v1/users/USER_ID/relationship?access_token=ACCESS TOKEN"];
NSURL *url=[NSURL URLWithString:initialURL];
NSString *key = [NSString stringWithFormat:#"action=follow"];
NSData *mastData = [key dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *mastLength = [NSString stringWithFormat:#"%d",[mastData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:mastLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:mastData];
NSURLConnection *con=[[NSURLConnection alloc]initWithRequest:request delegate:self];
[con start];
Also make sure to use proper scope while authenticating.
Add scope=like+comments+relationships in that authentication URL.
I am trying to perform a PUT. As a test, I execute a GET request on some JSON data and store this receivedData in a variable data that I have initialized elsewhere. I am able to decode the original data and everything looks fine. When I send it back I wipe out everything in the HTTP body of the URI I am PUTting to.
data = receivedData:
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:putURI]] autorelease];
[request setTimeoutInterval:10];
[request setHTTPMethod:#"PUT"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request addValue:self.token forHTTPHeaderField:#"Authorization"];
[request setHTTPBody:data];
NSLog(#"\nVerify existence of original data packet: \n%#\n\n",data);
self.putDeviceOnListConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
Any ideas what is wrong? Your help is greatly appreciated, as always.
I have found the problem with this. I have added a addValue:forHTTPHeaderField for for the length of the data packet and changed the content-type to "application/x-www-form-urlencoded.
I'm building a request that will be a simple http POST. Inside this post I need to add a few items and one of these is a large viewstate string that is pulled down during a previous request. What I've noticed is that the raw request needs to have all special chars escaped (like the below)
_EVENTTARGET=&_EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUENTM4MQ9kFgJmD2QWAmYPZBYCZg9kFgJmD2QWAgIBEGRkFgQCAQ9kFgICBw9kFgJmD2QWCmYPFgIeA3NyYwUpL2Fzc2V0cy9pbWFnZXMvc2l0ZW1haW5uYXYtcmVudG9ubGluZS5wbmdkAgEPFgIfAAUlL2Fzc2V0cy9pbWFnZXMvc2l0ZW1haW5uYXYtc3BhY2VyLnBuZ2QCAg8WAh8ABSUvYXNzZXRzL2ltYWdlcy9zaXRlbWFpbm5hdi1tb3ZpZXMucG5nZAIDDxYCHwAFJS9hc3NldHMvaW1hZ2VzL3NpdGVtYWlubmF2LXNwYWNlci5wbmdkAgQPZBYCZg9kFgZmDxYCHwAFLi9hc3NldHMvaW1hZ2VzL3NpdGVtYWlubmF2LWtpb3Nrc2Fub255bW91cy5wbmdkAgEPFgIfAAUlL2Fzc2V0cy9pbWFnZXMvc2l0ZW1haW5uYXYtc3BhY2VyLnBuZ2QCAg8WAh8ABSgvYXNzZXRzL2ltYWdlcy9zaXRlbWFpbm5hdi1idXlPbmxpbmUucG5nZAICD2QWAgIBD2QWAgIGD2QWAgIBD2QWAmYPZBYCAgIPEA8WAh4EVGV4dAVTUmVjb2duaXplIG1lIGZvciAxNCBkYXlzIChEbyBub3QgY2hlY2sgdGhpcyBib3ggaWYgeW91IGFyZSB1c2luZyBhIHNoYXJlZCBjb21wdXRlcilkZGRkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBVVjdGwwMCRjdGwwMCRjdGwwMCRjdGwwMCRNYWluQ29udGVudCRNYWluQ29udGVudCRNYWluQ29udGVudCRiYnhsb2dpbl83JGNoa1JlY29nbml6ZU1lNZH1xfrz8glwi2XmQJFTCJ0dMNk%3D&
But I'm not certain that I've done this in objective-c. Currently when I NSLog out the viewstate string it is still showing / and = characters.
Can anyone verify I'm on the right path here? And if not how would I convert the special chars in viewstate (ie - instead of = I should get %3D)?
- (void)doHttpPostWithViewState:(NSString *)viewstate
{
responseData = [[NSMutableData data] retain];
NSURL *url = [NSURL URLWithString:#"https://localhost/Login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSString* theBodyString = [[NSString alloc] initWithFormat:#"__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%#",viewstate];
NSData *requestData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[request setAllHTTPHeaderFields:headers];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
And finally, for local debugging purposes- how can I use NSLog to view the final (raw) string that will be sent to the client? Thank you in advance!
Update
Turns out this is a bug in the stringByAddingPercentEscapesUsingEncoding method
I've found the following to work from this blog post
NSString * cleanViewState = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)viewstate,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8 );
You're probably looking for the stringByAddingPercentEscapesUsingEncoding: method on NSString to %-encode your POST request.
Update:
If the NSString method isn't getting all the special characters you need, the next step is to drop down to the Core Foundation level function (CFURLCreateStringByAddingPercentEscapes), which gives you better control. See http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/