Sending key Value to server in IOS - http-post

Key is> hi
Value is> hello
I need to send this value to server.Consider my url is https://mywebsite/myserver/upload
How to send these value to server in IOS by making HTTP POST method.

This is how you can send key pair value as a part of your request body
NSString *myKeyValuePairString = #"hi=hello";
NSData *myRequestData = [NSData dataWithBytes:[myKeyValuePairString UTF8String] length:[myKeyValuePairString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: #"https://mywebsite/myserver/upload"]];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPBody: myRequestData];
if as a part of header
[request setValue:#"hello" forHTTPHeaderField:#"hi"];

Related

NSMutableURLRequest posting a JSON object to CakePHP appears as an Array

I send JSON data from Xcode in the following way:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
#"Test title", #"title",
#"Test option1", #"option1",
#"Test option2", #"option2", nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *url = [NSURL URLWithString:#"http://somedomain.com/posts/add"];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
[NSURLConnection connectionWithRequest:request delegate:self];
I write the received data in CakePHP to a file in the following way:
public function add()
{
if ($this->request->is('post'))
if ($this->RequestHandler->requestedWith('json')) {
file_put_contents('debug.txt', print_r($this->request->data, true));
}
}
}
and the data in the file ('debug.txt') looks like this:
Array
(
[option2] => Test option2
[title] => Test title
[option1] => Test option1
)
I know that the data being sent is in JSON format and I expect the received data to appear as JSON format rather than an Array in 'debug.txt'. Is this a correct assumption and if so what is going wrong?
I'm not sure what the problem is here, before you can do anything with that data in PHP you'd have to convert it to an array anyway, it seems the CakePHP requesthandler is doing this automatically for you.
If you really want the original json just json_encode() it back again.

ASIHttpRequest upload image

Hey i have a mac application with the following code:
NSURL *url;
url = [NSURL URLWithString:#"http://yfrog.com/api/xauth_upload"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setDelegate:self];
[request setUseCookiePersistence:NO];
[request setUploadProgressDelegate:self];
[request showAccurateProgress];
[request signRequestWithClientIdentifier:#"w" secret:#"x" tokenIdentifier:#"y" secret:#"z" usingMethod:ASIOAuthHMAC_SHA1SignatureMethod];
[request setPostValue:#"a" forKey:#"key"];
NSData *imageData = [[NSData alloc]initWithContentsOfFile:[draggedFilenames objectAtIndex:0]];
[request setPostValue:imageData forKey:#"media"];
[request startAsynchronous];
But the problem is i always get this response from yfrog servers:
So something is wrong with the image upload. On iPhone it works like this:
[request setData:UIImageJPEGRepresentation(picture, 0.8) withFileName:#"filename.jpg" andContentType:#"image/jpeg" forKey:#"media"];
But this doesn't work cocoa(mac) because there is no method like UIIMageJPEGRepresentation.
Also the authentication works, this cant be the problem. If you ask you about this method signRequestWithClientIdentifier it is from the asihttprequest+oauth wrapper from here:
https://github.com/keybuk/asi-http-request-oauth
So how can i upload the image correctly ?
Thanks so much.
NSData* NSImageJPEGRepresentation(NSImage* image, CGFloat compressionQuality)
{
if(nil == image)return nil;
NSDictionary *dict;
dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:compressionQuality],
NSImageCompressionFactor,
nil];
NSBitmapImageRep* imageRep;
imageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
return [imageRep representationUsingType:NSJPEGFileType
properties:dict];
}

Xcode, can't send UTF-8 Text

I am trying to send a post value to my server.
It successfully send English characters.
This code is for finding friend, and it can't send UTF-8 text.
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
/*
Update the filtered array based on the search text and scope.
*/
if(![searchText isEqualToString:#""]){
NSUserDefaults * userdef = [NSUserDefaults standardUserDefaults];
NSString *encodedSearchText = [searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString * uploadUrl = [NSString stringWithFormat:#"%#/%#" , GPON_URL , GPON_URL_SEARCHFRIEND];
NSURL *url = [NSURL URLWithString:uploadUrl];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:encodedSearchText forKey:#"u_id"];
[request setPostValue:[userdef objectForKey:KEY_USER_ID] forKey:#"s_username"];
[request startSynchronous];
[request setShouldAttemptPersistentConnection:NO];
NSString *response = [request responseString];
SBJsonParser * parser = [[[SBJsonParser alloc] init] autorelease];
NSDictionary * json = (NSDictionary *)[parser objectWithString:response];
[searchMember removeAllObjects];
if( [[json objectForKey:#"result"] isEqual:#"YES"] ){
[searchMember addObjectsFromArray:[json objectForKey:#"data"]];
[self.tableView reloadData];
}
}
}
here is my code. can you see what cause the error?
You don't appear to be setting the string encoding of the request; try:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setStringEncoding:NSUnicodeStringEncoding];
Also, this is a very poor way of determining if an NSString is empty:
if (![searchText isEqualToString:#""])
Use the length method instead:
if ([searchText length] > 0)

Error with headers of NSMutableRequest

i had a problem with a NSMutableURLRequest, i want to translate this
curl -b $cookie -F "data=foo" -F "user=bar" http://some/stuff.cgi -H 'X-Requested-With: XMLHttpRequest
my code is
NSString *params = [NSString stringWithFormat:#"data=%#&user=bar", aUrl];
NSURL *url = [NSURL URLWithString:[[NSString alloc] initWithFormat:[NSString stringWithFormat:#"http://%#:%d/stuff.cgi", _host, _port]]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5.0];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding ]];
[request setValue:[NSString stringWithFormat:#"http://%#/stuff.php", _host] forHTTPHeaderField:#"Referer"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"XMLHttpRequest" forHTTPHeaderField:#"X-Requested-With"];
NSArray *availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://%#", _host]]];
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies];
[request setAllHTTPHeaderFields:headers];
NSLog(#"headers: %#", [request allHTTPHeaderFields]);
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
...
but it don't work, i'm make search without results and i' don't know where is the problem.
Thanks.
Solved, just specifie length
[request setValue:[[NSString alloc] initWithFormat:#"%d", [params length]] forHTTPHeaderField:#"Content-Length"];

Sending a POST request from Cocoa to Tumblr

This code snippet isn't working, I'm getting an "Authentication Failed." response from the server. Any ideas?
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:
[NSURL URLWithString:#"http://www.tumblr.com/api/write"]];
[request setHTTPMethod:#"POST"];
[request addValue:_tumblrLogin forHTTPHeaderField:#"email"];
[request addValue:_tumblrPassword forHTTPHeaderField:#"password"];
[request addValue:#"regular" forHTTPHeaderField:#"type"];
[request addValue:#"theTitle" forHTTPHeaderField:#"title"];
[request addValue:#"theBody" forHTTPHeaderField:#"body"];
NSLog(#"Tumblr Login:%#\nTumblr Password:%#", _tumblrLogin, _tumblrPassword);
[NSURLConnection connectionWithRequest:request delegate:self];
[request release];
Both _tumblrLogin and _tumblrPassword are run through stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding elsewhere in my code. My login email is of the form "address+test#test.com". It works just fine for logging in directly to tumblr, but I'm wondering if the "+" character is causing problems with the encoding? It's not being escaped. Should it be?
Thanks to Martin's suggestion, I'm now using CFURLCreateStringByAddingPercentEscapes to escape my login and password. I'm still having the same issue, though, my Authentication is failing.
The problem is that you are not creating a proper HTTP POST request. A POST request requires a properly formatted multipart MIME-encoded body containing all the parameters you want to send to the server. You are trying to set the parameters as HTTP headers which won't work at all.
This code will do what you want, note especially the NSString categories that create a valid Multipart MIME string:
#interface NSString (MIMEAdditions)
+ (NSString*)MIMEBoundary;
+ (NSString*)multipartMIMEStringWithDictionary:(NSDictionary*)dict;
#end
#implementation NSString (MIMEAdditions)
//this returns a unique boundary which is used in constructing the multipart MIME body of the POST request
+ (NSString*)MIMEBoundary
{
static NSString* MIMEBoundary = nil;
if(!MIMEBoundary)
MIMEBoundary = [[NSString alloc] initWithFormat:#"----_=_YourAppNameNoSpaces_%#_=_----",[[NSProcessInfo processInfo] globallyUniqueString]];
return MIMEBoundary;
}
//this create a correctly structured multipart MIME body for the POST request from a dictionary
+ (NSString*)multipartMIMEStringWithDictionary:(NSDictionary*)dict
{
NSMutableString* result = [NSMutableString string];
for (NSString* key in dict)
{
[result appendFormat:#"--%#\r\nContent-Disposition: form-data; name=\"%#\"\r\n\r\n%#\r\n",[NSString MIMEBoundary],key,[dict objectForKey:key]];
}
[result appendFormat:#"\r\n--%#--\r\n",[NSString MIMEBoundary]];
return result;
}
#end
#implementation YourObject
- (void)postToTumblr
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:
[NSURL URLWithString:#"http://www.tumblr.com/api/write"]];
[request setHTTPMethod:#"POST"];
//tell the server to expect 8-bit encoded content as we're sending UTF-8 data,
//and UTF-8 is an 8-bit encoding
[request addValue:#"8bit" forHTTPHeaderField:#"Content-Transfer-Encoding"];
//set the content-type header to multipart MIME
[request addValue: [NSString stringWithFormat:#"multipart/form-data; boundary=%#",[NSString MIMEBoundary]] forHTTPHeaderField: #"Content-Type"];
//create a dictionary for all the fields you want to send in the POST request
NSDictionary* postData = [NSDictionary dictionaryWithObjectsAndKeys:
_tumblrLogin, #"email",
_tumblrPassword, #"password",
#"regular", #"type",
#"theTitle", #"title",
#"theBody", #"body",
nil];
//set the body of the POST request to the multipart MIME encoded dictionary
[request setHTTPBody: [[NSString multipartMIMEStringWithDictionary: postData] dataUsingEncoding: NSUTF8StringEncoding]];
NSLog(#"Tumblr Login:%#\nTumblr Password:%#", _tumblrLogin, _tumblrPassword);
[NSURLConnection connectionWithRequest:request delegate:self];
[request release];
}
#end
As per the answers to this question, stringByAddingPercentEscapesUsingEncoding: doesn't perform a full escape encoding. For whatever reason, the CoreFoundation version of this method does, however:
[(NSString *) CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)[[self mutableCopy] autorelease], NULL,
CFSTR("=,!$&'()*+;#?\n\"<>#\t :/"), kCFStringEncodingUTF8) autorelease];
You can also use NSMutableString's replaceOccurencesOfString:withString:options: method to do the replacement manually, but that method is more repetitive and verbose. (See here.)

Resources