I am stuck with an issue in simple request response in iOS, I am getting blank response in request a url with one post parameter, where the url as it is perfectly working in android and webbrowser
Friends in detail, I have to call
http://example.com/GetCountries
with below http post params
"key"="Abcd1234"
it is working before, but from last few days it is not working, if I check NSError it is showing me The network connection was lost.
and one more thing noticeable here is same server code is on different url and it is working fine, and that url you can test as below
http://example.com/GetCountries
with below http post params
"key"="Abcd1234"
Here is the dropbox link for testing ios source code and also the folder contains Web services test.htm file to test that same url with same post parameter working in browser but not in ios device.
Testing code:
https://dl.dropboxusercontent.com/s/lqrl5b95j2s54mm/Testing.zip?token_hash=AAFgoNfUpQ4FkeswnPdGiMVzdMtSM6js9KySJm_OH6lZXQ&dl=1
thank you
So I could not get the form per se to work but was able to recraft it to work. Note a few things:
you should convert to ARC!
you need a strong reference to the connection so you can release it later on (and not in a delegate method!)
you need the delegate connectionSucceeded method (to record response whatever!)
CODE:
- (void)asynchronousRequest
{
[activity startAnimating];
NSString *requesturl = lblURL.text;
NSLog(#"requesturl=%#", requesturl);
NSURL *theURL = [NSURL URLWithString:requesturl];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"content-type"];
[request setURL:theURL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *str = [NSString stringWithFormat:#"key=%#", [self URLencodedString:#"Abcd1234"]];
NSLog(#"BODY: %#", str);
NSData *body = [str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"URL : %#", requesturl);
NSLog(#"REQ : %#", request);
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%u", [body length]] forHTTPHeaderField:#"Content-Length"];
NSLog(#"AllFields : %#", [request allHTTPHeaderFields]);
NSLog(#"HTTPBody : %#", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
NSLog(#"HTTPMethod : %#", [request HTTPMethod]);
self.activeDownload = [NSMutableData data];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
assert(conn);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
assert([response isKindOfClass:[NSHTTPURLResponse class]]);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(#"GOT %d", [httpResponse statusCode]);
}
- (NSString *)URLencodedString:(NSString *)s
{
CFStringRef str = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)s, NULL, (CFStringRef)#"!*'();:#&;=+$,/?%#[]", kCFStringEncodingUTF8);
NSString *newString = [(NSString *)str stringByReplacingOccurrencesOfString:#" " withString:#"+"];
if(str) CFRelease(str);
return newString;
}
EDIT: Modified Code that still didn't work:
- (void)asynchronousRequest
{
[activity startAnimating];
NSString *boundary = #"1010101010"; // DFH no need for the leading '--'
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
NSMutableDictionary *postVariables = [[NSMutableDictionary alloc] init];
[postVariables setValue:#"Abcd1234" forKey:#"key"];
NSString *requesturl = lblURL.text;
NSMutableString *myStr = [[NSMutableString alloc] init];
NSString *str;
// DFH - strategy is to have each line append its own terminating newline/return
str = [NSString stringWithFormat:#"--%#\r\n",boundary]; // DFH initial boundary
[myStr appendString:str];
NSArray *formKeys = [postVariables allKeys];
for (int i = 0; i < [formKeys count]; i++) {
str = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n%#\r\n",[formKeys objectAtIndex:i],[postVariables valueForKey:[formKeys objectAtIndex:i]]];
[myStr appendString:str];
str = [NSString stringWithFormat:#"--%#\r\n",boundary]; // DFH mid or terminating boundary
[myStr appendString:str];
}
NSLog(#"BODY: %#", myStr);
NSData *body = [myStr dataUsingEncoding:NSUTF8StringEncoding];
requesturl = [self encodeStringForURL:requesturl];
NSLog(#"requesturl=%#", requesturl);
NSURL *theURL = [NSURL URLWithString:requesturl];
self.activeDownload = [NSMutableData data];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:theURL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"]; // DFH you add addValue, I always use setValue
NSLog(#"URL : %#", requesturl);
NSLog(#"REQ : %#", request);
NSLog(#"ContentType \"%#\"", contentType);
if(body)
{
[request setHTTPBody:body];
}
NSLog(#"AllFields : %#", [request allHTTPHeaderFields]);
NSLog(#"HTTPBody : %#", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
NSLog(#"HTTPMethod : %#", [request HTTPMethod]);
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
assert(conn);
}
I have used ASIHTTP Library and my problem is solved
Related
I am new to IOS i need to pass three parameter in POST method.my parameter are (1)str (2)str1 (3)str2.this three parameter are fetch from different url in string format.
coding for POST method:
i need to add these parameter in method?i already added str parameter but i am struggling to pass other two(str1,str2) parameter.
-(void) sendDataToServer : (NSString *) method params:(NSString *)str{
NSString *post = [NSString stringWithFormat:#"branch_id=%#",str];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
mutableData = [[NSMutableData alloc]init];
}
}
Viewdidload:
here also i want to str1 and str2 parameter.
[self sendDataToServer :#"POST" params:str];
you can implement in multiple ways
Choice-1
-(void) sendDataToServer : (NSString *) method firstparams:(NSString *)firststr secondparam:(NSString *)secondstr thirdparam:(NSString *)thirdstr{
NSString *post = [NSString stringWithFormat:#"branch_id=%#&xxxx=%#&yyyyy=%#",firststr,secondstr,thirdstr];
// continue your works as its same flow
call method like
[self sendDataToServer :#"POST" firstparams:#"yourbranchID" secondparam:#"xxxValue" thirdparam:#"yyyyvalue"];
Choice-2
what ever you did is correct, just modify some code in viewdidload or else
// add all values in one string using stringWithFormat
NSString *str = [NSString stringWithFormat:#"branch_id=%#&xxxx=%#&yyyyy=%#",firststr,secondstr,thirdstr];
// and pass the param to web call
[self sendDataToServer :#"POST" params:str];
call method as
-(void) sendDataToServer : (NSString *) method params:(NSString *)str{
// no need of this line
// NSString *post = [NSString stringWithFormat:#"branch_id=%#",str];
// directly called the str in her
NSData *postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post length]];
/.... as its is continue the same work
instead of passing it as NSString just add the three string in a globally declared array and add objects to it and send it to web service.
or create them as NSDictionary and convert them as json string to web service.
NSDictionary *params = #{#"param1": str1, #"param2": str2, #"param3": str3 };
[self sendDataToServer :#"POST" params:params];
-(void) sendDataToServer : (NSString *) method params:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:jsonString forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
mutableData = [[NSMutableData alloc]init];
}
}
}
I need to bind parameters in an object and pass the object as a POST request to receive a successful piece of information from an API.
{
customer = {
"auth_token" = "";
"device_id" = 3e708bf1a49cdd06;
"email_address" = "abc#xyz.in";
name = abc;
number = 1234567890;
"resend_token" = true;
};
}
This is the object that I need to send along with the post request. But when I convert it into a string and post it, the entire object becomes the key and the value becomes nil. It gets posted as {"{customer.....}=>nil}.
The object should be posted as
{"customer:
{"auth_token":"","device_id":"3e708bf1a49cdd06","email_address":"abc#xyz.in",
"name":"abc","number":"1234567890","resend_token":"true"}}
This my current attempt:
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
NSString *postString = [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setHTTPMethod:#"POST"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
A lot of the code used here was used without a proper understanding and directly taken from other StackOverflow answers, so please excuse any bad programming practice.
How can I do this? Any help is appreciated. Thank you.
you can try below code.Instead of converting data to string set it as HTTPBody like
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = temp;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setHTTPMethod:#"POST"];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Following is the sample code for sending a POST request to server.
-(void)doRequestPost:(NSString*)url andData:(NSDictionary*)data{
requestDic = [NSDictionary dictionaryWithDictionary:data];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:nil];
NSString *jsonString=[[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSStringEncodingConversionAllowLossy];
NSLog(#"Request Object:\n%#\n",data);
NSLog(#"Request String:\n%#\n",jsonString);
NSMutableURLRequest *theReq=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[theReq addValue: #"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theReq setHTTPMethod:#"POST"];
[theReq addValue:[NSString stringWithFormat:#"%lu",(unsigned long)[jsonString length]] forHTTPHeaderField:#"Content-Length"];
[theReq setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
connection = [NSURLConnection connectionWithRequest:theReq delegate:self];
}
May this help lot and resolve your problem.
NSString *post =[[NSString alloc] initWithFormat:#"id=%d&restaurant_name=%#", restaurnt_Id, _rest_NameTxt.text];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:EDIT_RESTAURANT_API];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"APPLICATION/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"APPLICATION/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
_responseData = [[NSMutableData alloc] init];
[NSURLConnection connectionWithRequest:request delegate:self];
pragma mark - connection methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_responseData setLength:0];
[_responseCityData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseData appendData:data];
[_responseCityData appendData:data];
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[COMMON showErrorAlert:#"Internet Connection Error!"];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
responseString = [responseString stringByReplacingOccurrencesOfString:#"\n" withString:#" "];
NSLog(#"%#", responseString);
}
Make your task in connectionDidFinishLoading method
Below code i wrote for sending two images. But i failed to find the code why its not working. i am new to iOS and even stackoverflow. Still am thinking the code is ok. just help me to find my mistake. how i modify the code to able to send two images with different services(each service have a separate url).
NSString *requestString =[NSString stringWithFormat:#"requestUserId=%#&CategoryId=%#&Continent=%#&Country=%#&City=%#&Gender=%#&ImageName=%#&AgeRange=%#",userID,CategoryId1,continentTextfield.text,countrytextfield.text,citytextfield.text,GenderText.text,imagename,ageTextfield.text];
NSLog(#"request%#",requestString);
NSString *url=[NSString stringWithFormat:#"http://37.187.152.236/UserImage.svc/InsertObjectImage?%#",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage, 0.2f);
[request addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:data]];
[request setHTTPBody:body];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request delegate:self];
if (connReq) {
NSLog(#"Connection Sucessful");
receivedData = [[NSMutableData alloc]init];
}
else {
NSLog(#"failed");
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Status code: %d", [response statusCode]);
NSLog(#"respdata%#",respData);
if ([response statusCode]==200)
{
self.userId=[[NSUserDefaults standardUserDefaults]objectForKey:#"Sendd"];
NSLog(#"recievedData%#",receivedData);
NSString *requestString1 =[NSString stringWithFormat:#"requestUserId=%#&ImageId=%#&=ImageName%#",userID,compareId,imagename];
NSLog(#"%#",requestString1);
NSString *url1=[NSString stringWithFormat:#" http://37.187.152.236/UserImage.svc/UpdateObjectImage?%#",requestString1];
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] init] ;
[request1 setURL:[NSURL URLWithString:url1]];
[request1 setHTTPMethod:#"POST"];
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request1 setValue:contentType forHTTPHeaderField:#"Content-Type"];
NSData *data = UIImageJPEGRepresentation(chosenImage, 0.2f);
[request1 addValue:#"image/JPEG" forHTTPHeaderField:#"Content-Type"];
NSMutableData *body1 = [NSMutableData data];
[body1 appendData:[NSData dataWithData:data]];
[request setHTTPBody:body1];
NSData *returnData;
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
NSURLConnection *connReq = [NSURLConnection connectionWithRequest:request delegate:self];
if (connReq) {
NSLog(#"Connection Sucessful");
receivedData = [[NSMutableData alloc]init];
}
else {
NSLog(#"failed");
}
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Status code: %d", [response statusCode]);
NSLog(#"respdata%#",respData);
homeViewController *homVew =[[homeViewController alloc]initWithNibName:#"homeViewController" bundle:nil];
self.navigationItem.hidesBackButton = YES;
[self.navigationController pushViewController:homVew animated:YES];
}
I've search and try many different solutions but without luck.
I am trying to make a JSON Request to my server, it works for sure because I've tested it in PHP (simple call, it receives string name and string password and check into the database if the user is correct). The request should receive back a JSON with property "success" only (which could be "true" or "false").
Here is my code:
- (void)logonService:(NSString *) name widthArg2:(NSString *) password {
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://46.51.169.145/ios/index.php/user/login/"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
//setting json fields
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
//prepare output data
NSString *in1;
NSDictionary *outputData = [NSDictionary dictionaryWithObjectsAndKeys:in1, #"success", nil];
NSError *error = nil;
NSData *jsonOutputData = [NSJSONSerialization dataWithJSONObject:outputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonOutputString = [[NSString alloc] initWithData:jsonOutputData encoding:NSUTF8StringEncoding];
//set json string to body data
NSData *requestInputBodyData = [jsonOutputString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody: requestInputBodyData];
//prepare input data
NSString *input = [NSString stringWithFormat:#"&name=%#&password=%#",name,password];
//Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.
NSData *inputData = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//calculate length of post data
NSString *inputLength = [NSString stringWithFormat:#"%d",[inputData length]];
//Set HTTP header field with length of the post data.
[request setValue:inputLength forHTTPHeaderField:#"Content-Length"];
//encode type
//[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
//add it to http body
[request setHTTPBody:inputData];
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn){
NSLog(#"Connection Successful");
}else{
NSLog(#"Connection could not be made");
}
}
The delegate DidReceiveData fires correctly but the result is always NIL:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *jsonResponseData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"RESULT1: %#", jsonResponseData);
[_responseData appendData:data];
}
Thank you, hope someone can help me!
thanks a lot for the comments, I finally fix it, and after that I decided to starting using a JSON library --> https://github.com/stig/json-framework/
This is how I finally have the code:
//prepare connection
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#user.php", _urlServer]];
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setObject:#"login" forKey:#"action"];
[data setObject:username forKey:#"username"];
[data setObject:password forKey:#"password"];
//start connection
// Create the request, if there is a connection going on just cancel it.
[_connection cancel];
//initialize new mutable data
NSMutableData *receivedData = [[NSMutableData alloc] init];
_receivedData = receivedData;
//initialize the url which will be fetched
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
//set http method
[request setHTTPMethod:#"POST"];
//initialize a post data
NSString *dataString = [[NSString alloc] init];
for(id key in data) {
id value = [data objectForKey:key];
//keys string
NSString *newData = [NSString stringWithFormat:#"&%#=%#", key, value];
dataString = [dataString stringByAppendingString: newData];
}
//set request content type we MUST set this value.
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
//set post data of request
[request setHTTPBody:[dataString dataUsingEncoding:NSUTF8StringEncoding]];
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
_connection = connection;
//NSLog(#"Sending request with parameters: %#", dataString);
//begin the connection
[_connection start];
And its working like a charm. Next step is to authenticate somehow, right now connection is open to the world.
Currently I have a string that I want to POST to a URL.
It works perfectly fine except when it encounters special characters like "&", and "?". It will not POST any data that comes after that. For example, if I have a string "I am something & something?", it will only POST "I am something". As for "?", it will be converted to '2' after it has been posted.
reason = 'What see see! Are you sure'2''
I am pretty sure that it must have something to do with encoding as I can see "I am something & something?" as it is just before I set the encoding:
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
I have also tried the encodings below with no success:
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSData *postData = [post dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSData *postData = [post dataUsingEncoding:NSISOLatin1StringEncoding];
Below are my codes from postData onwards:
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
//NSLog(#"PostData: %#", postData);
NSString *check = [[NSString alloc] initWithData:postData encoding:NSASCIIStringEncoding];
NSLog(#"check string = %#", check);
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:strURLQueryString]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err=nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *strResponse = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#", strResponse);
if(err!=nil) {
NSLog(#"Error: %#", [err description]);
}
Please assist.
Your help(s) are appreciated.
There's probably a better answer out there somewhere, but this class extension has been working for me for awhile. I cobbled together the % escapes by looking at a few posts...
// NSString+URLEncoding.h
#interface NSString (NSString_URLEncoding)
- (NSString *)urlEncodeUsingEncoding:(CFStringEncoding)encoding;
- (NSString *)urlEncode;
#end
// NSString+URLEncoding.m
#implementation NSString (NSString_URLEncoding)
- (NSString *)urlEncodeUsingEncoding:(CFStringEncoding)encoding {
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(__bridge CFStringRef)self,
NULL,
CFSTR("!*'();:#&=+$,/?%#[]"),
encoding));
}
- (NSString *)urlEncode {
return [self urlEncodeUsingEncoding:kCFStringEncodingUTF8];
}
Then in somer other class to send a string...
// SomeOtherClass.m
#import "NSString+URLEncoding.h"
NSString *encodedString = [#"This & this? are 'challenging' to !% encode" urlEncode];