NSURLConnection sends GET request instead of POST request - ios

I'm trying to make a POST request using NSURLConnection. I use Charles to debug and Charles every time says that the method is GET. I've tried all different ways and can't get it to work. I am NOT using JSON.
-(void)getList
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://example.com/api/getList"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *radius = #"15";
NSString *latitude = #"-117.820833";
NSString *longitude = #"34.001667";
NSString *parameters = [NSString stringWithFormat:#"longitude=%#&latitude=%#&radius=%#", longitude,latitude, radius];
NSLog(#"PARAMS = %#", parameters);
NSData *data = [parameters dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/plain" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#"RESULT = %#", responseString);
}
Does anybody know what am I doing wrong? When I access my web service it seems like I'm not posting anything. I'm getting empty response.
Please help with any ideas. I pretty much have to make a simple POST request. Maybe someone can help me debug this better.

If the server is redirecting your request for some reason (perhaps authentication) then the POST information can get lost.

Related

Unsupported URL when sending Json value as argument in GET method

Code:
arrValues = [[NSMutableArray alloc]initWithObjects:#"Chennai", nil];
arrKeys = [[NSMutableArray alloc]initWithObjects:#"loc", nil];
dicValue = [NSDictionary dictionaryWithObjects:arrValues forKeys:arrKeys];
NSString *strMethodName = #"agentuserlist";
strUrlName = [NSString stringWithFormat:#"%#%#?filters=%#",appDelegate.strURL, strMethodName, dicValue];
//strUrlName = [strUrlName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strUrlName] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:250.0];
[request setHTTPMethod:#"GET"];
[request setHTTPShouldHandleCookies:YES];
[request setValue:#"zyt45HuJ70oPpWl7" forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSError *error;
NSURLResponse *response;
NSData *received = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSLog(#"error:%#", error);
NSString *strResponse = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
NSLog(#"response :%#", strResponse);
I try to send json argument through get method.It gives error as "unsupported url(-1002)".
The URL is working fine when I checked with Postman. I am unable to find out the problem.
Where I went wrong?
I think the problem lies in how you encode your NSDictionary in the NSURL.
You probably want your URL to look like this: http://my domain.com/agentuserlist?loc=Chennai. But the raw encoding of the NSDictionary inside the NSURL doesn't produce this result.
You can follow the accepted answer
from this question to get an idea of how to transform an NSDictionary into a regular list of URL parameters (with proper encoding of dictionary values: don't forget the stringByAddingPercentEscapeUsingEncoding part): Creating URL query parameters from NSDictionary objects in ObjectiveC

Consume ASP web service with JSON response on iOS

I am trying to call a web service that is developed with ASP.NET. The purpose is to pass a username and password to the web service to simulate a log-in procedure.
In order to call the service i used the following method:
NSError *errorReturned = nil;
NSString *urlString = #"http:myDomain/myMethod?Operation=SignIn";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:#"test" forKey:#"userName"];
[dict setObject:#"test" forKey:#"passWord"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&errorReturned];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
NSLog(#"%#", errorReturned);
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
}
After running the app and clicking on the UIButton that fires the above method, nothing is shown in the console window.
The service returns the response in JSON format.
I want to know if i am missing something here since i am neither getting an error nor success log?
Any help would be appreciated!
Thank you.
Granit
A couple of thoughts:
If this method is getting called, you'd see something, even if retVal was empty and your
NSLog(#"%#", retVal);
just logged the app name and timestamp. Maybe change that NSLog to
NSLog(#"retVal = %#", retVal);
to remove any ambiguity. Or put in breakpoints in your code and single step through it to see what path the app takes.
Are you confident of your server interface? For example, is it possible that the Operation value of SignIn belongs in the JSON request, itself? Also, some services are case sensitive, so you might want to check that, too.
I don't know what access you have to the server, but it would be worthwhile to check the logs to make sure the request was received, possibly temporarily adding some logging within the code so you can confirm that the parameters were all received properly. Or, if nothing else, make sure that the server properly logs/reports any errors.
BTW, your instantiation of theResponse is unnecessary, and should just be
NSURLResponse *theResponse = nil;
The sendSynchronousRequest call doesn't populate an existing NSURLResponse instance, but rather creates a new instance and updates theResponse to point to it.
You should fix your request first, but you probably want, at the very least, to change this to use sendAsynchronousRequest instead of sendSynchronousRequest. You should never do synchronous calls on the main thread.
I solved my issue by using ASIHHTPRequest. Also i checked the server interface and it turned out that the parameters had to be sent with the URL.
-(void)signInAction:(id)sender{
NSURL *url = [NSURL URLWithString:#"http://mydomaain.com/UserService/SignIn/test/test"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDidFinishSelector:#selector(requestCompleted:)];
[request setDidFailSelector:#selector(requestError:)];
[request setDelegate:self];
[request setRequestMethod:#"GET"];
[request startAsynchronous];
}
- (void)requestCompleted:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
//[responseString UTF8String];
NSLog(#"ResponseString:%s",[responseString UTF8String]);
}
- (void)requestError:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog(#"Error:%#",[error description]);
}

Connection to Server successfully but got some crap after json format strings

I have successfully connected to a server, and getting correct json format String from it. Somehow 9 out of 10 times it return with something extra.. like some crap code i don't recognize. sometimes its just incomplete data. I wonder what I did wrong or what I didn't do..
does anyone has the same problem? and how can I fix it?
NSURL *siteURL = [NSURL URLWithString:tempSiteString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:siteURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:30.0];
NSString *myRequestString = [NSString stringWithFormat:#"data=%#", sqlString];
NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[sqlString length]];
[request setHTTPMethod: #"POST" ];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPBody: myRequestData ];
NSURLResponse *response;
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request
returningResponse: &response
error: &error];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
here is the code i change the received string to json
NSDictionary *tempNSDictionary = [resultString JSONValue];
if(tempNSDictionary.count==0)
{
return nil;
}
//NSLog(#"Check Point after dictionary");
NSArray *tempNSArray;
if(tempNSDictionary)
{
//NSLog(#"Check Point getArrayFromJsonString 1");
tempNSArray = [tempNSDictionary objectForKey:#"object_name"];
//NSLog(#"Check Point getArrayFromJsonString 2");
}
return tempNSArray;

IOS to REST-ful MVC Api Service - [Get] works, but parameters don't reach server with [Post]

I think the title explains it. I can reach the Get functions on my api controllers just fine. I can reach the Post method, but my parameter (macAddress) is null. I've tried many variations of this code in xcode:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",baseURL,controller]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *postString = #"macAddress=testestest";
NSData *myRequestData = [ NSData dataWithBytes: [ postString UTF8String ] length: [ postString length ] ];
[request setHTTPBody:myRequestData];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
and the controller:
public String Post([FromBody]string macAddress)
{
//......
}
(I'm aware that I'm using synchronous requests and nil response/errors, just trying to figure out this aspect)
Thanks for the help.
It looks like you have your *postString without the [NSString stringWithFormat method]. I use the following code with my own restful API.
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"rsdevicetoken"];
NSString *postString = [NSString stringWithFormat:#"token=%#&active=%#&draw=%#&result=%#&message=%#",deviceToken,allNotify, draw, results, message];
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.someurl.com/updateSubscriptions"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#", data);
Hopefully this will help you.
It's a wild guess but if your macAddress post param has the following format: 01:23:45:67:89:ab you need to url encode the ':' to '%3A'.

NSMutableURLRequest transform to ASIFormDataRequest

I have writen the fellowing code:
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
postStr = #"user_name=Thomas Tan&phone=01234567891&password=123456";
NSData *myRequestData = [NSData dataWithBytes:[postStr UTF8String] length:[postStr length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: myRequestData];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
it works well,but now I want to use asihttprequest framework,so how to change the above code,I have writen the code,but it can't get the correct result and just get the server error infomation.so what's the problem?
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *requeset = [ASIFormDataRequest requestWithURL:url];
[requeset setRequestMethod:#"POST"];
[requeset setPostValue:#"Thomas Tan" forKey:#"user_name"];
[requeset setPostValue:#"01234567891" forKey:#"phone"];
[requeset setPostValue:#"123456" forKey:#"password"];
[requeset startSynchronous];
NSError *error = [requeset error];
if (!error) {
NSString *re = [requeset responseString];
NSLog(#"%#",re);
}
NSLog(#"%#",error);
thank you in advance.
UPDATE:
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request appendPostData:[#"user_name=Thomas Tan&phone=01234567891&password=123456" dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *re = [request responseString];
NSLog(#"%#",re);
}
NSLog(#"%#",error);
I use the above code ,It also can't get the same result,and error is not nil.
Your ASIHTTP code is not doing the same thing as your NSURLConnection code.
ASIFormDataRequest will automatically:
set the Content-Type header to application/x-www-form-urlencoded
URL-encoded your parameters
That's usually exactly what you want, but if you're getting the correct behavior with your NSURLConnection code and incorrect with ASIHTTP, then you need to change to a custom ASIHTTP POST and use ASIHTTPRequest, not ASIHTTPFormDataRequest, and then manually set the Conten-type back to application/x-www-form-urlencoded:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Content-Type" value:#"application/x-www-form-urlencoded"];
[request appendPostData:[#"user_name=Thomas Tan&phone=01234567891&password=123456" dataUsingEncoding:NSUTF8StringEncoding]];
Doing this, and inspecting exactly what was sent to the server using Wireshark, I can see that the POST data sent is still not quite identical (ASIHTTP on the left, NSURLConnection on the right):
But the content type, length, and actual data is identical.
At this point, I'd expect your server to return the same result.
If it still doesn't, you can edit the ASIhTTP request parameters to match.

Resources