NSMutableURLRequest get -1012 http status code instead of 401 - objective-c

I have to pass Authorization token in NSMutableURLRequest , My query is Whenever I have to pass Correct token than I am getting good response with https Status (200.. etc). but whenever I have to pass wrong Authorization token Than I am getting following response insted of http status code 401
* with wrong token response * (I had hide my query htpp:....)
Error Domain=NSURLErrorDomain Code=-1012 "(null)" UserInfo={NSErrorFailingURLStringKey=http......, NSUnderlyingError=0x60800024c420 {Error Domain=kCFErrorDomainCFNetwork Code=-1012 "(null)" UserInfo={_kCFURLErrorAuthFailedResponseKey={url = http.....}}}, NSErrorFailingURLKey=http....}
** here is my code **
// parameter in dictionary
NSDictionary *parameters = #{ #"user_id": [NSNumber numberWithInt:1]};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:NSJSONWritingPrettyPrinted
error:&error];
// Convert dictionary to Json String
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
jsonparameter = jsonString;
}
NSData *postData = [jsonparameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:SiteAPIURL,wsname]]];
NSString *Accesstoken = [NSString stringWithFormat:#"Bearer %#",tokenInfo.access_token];
// Set Access token
[request setValue:Accesstoken forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSHTTPURLResponse __autoreleasing *response;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%#",error.localizedDescription);
NSLog(#"Status code =%ld",(long)response.statusCode);

401 is server generated error. -1012 is system generated error. This sometimes may be because of app is keeping cached certificates and certificate on the server has been changed so they don't match. Clearing Caches and Preferences folders from app's home directory will delete the old certificate data and app will have to download the new one from the server and you problem will be solved.

Related

.NET Web Api Token Authentication Rest Service "Get" Method in Objective-C

I'm trying to access the following URL:
http://appointmentreminder4.azurewebsites.net/Profile
This URL uses a "Get" method, and is supposed to provide JSON results. Before accessing the URL, you need to login using your Email Address and Password. After logging in successfully, the Web API issues a token. This token is used in ALL communications going forward.
I am currently unable to retrieve the token in Objective-C. I have attempted to google this problem, but I cannot figure out:
1) How to get the token
2) How to get the JSON output from the URL.
Here is the code I have written so far that returns neither the JSON, nor the token:
NSDictionary *postDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"Email Adress", #"MyEmailAddress",
#"Password", #"MyPassword",
nil];
NSError *error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:kNilOptions error:&error];
NSURLResponse *response;
NSData *localData = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://appointmentreminder4.azurewebsites.net/home"]];
[request setHTTPMethod:#"POST"];
if (error == nil)
{
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
// Send the request and get the response
localData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:localData encoding:NSASCIIStringEncoding];
NSLog(#"Post result : %#", result);
}
If the above link fails, use this link to navigate to the specific page:
http://appointmentreminder4.azurewebsites.net/home

Objective C NSMutableURLRequest GET request returns null JSON

trying get Data from server using #"GET" request,
this following code returns null all time:
is anybody finding an issue with my following code?
or it's can be server side Issue..
?
thank for your help!
+ (id)sendParam:(NSString*)ParamString url:(NSString*)url{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
NSString *post = ParamString;
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request setURL:[NSURL URLWithString:url]];
NSLog(#"postLength =%#",postLength);
[request setHTTPBody:postData];
[request setHTTPMethod:#"GET"];
[request addValue:ParamString forHTTPHeaderField:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSMutableArray*jsonReturn = [[NSMutableArray alloc]init];
jsonReturn = (NSMutableArray*)[NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
NSLog(#"jsonReturn %#",jsonReturn);
return jsonReturn;
}
after Editing:
+ (id)sendParam:(NSString*)ParamString url:(NSString*)url{
NSString*StringGETMETHOD = [NSString stringWithFormat:#"%#%#",url,ParamString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:StringGETMETHOD]];
[request setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"aData=%#",aData);
if (aData) {
jsonReturn=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
NSLog(#"jsonReturn %#",jsonReturn);
}
If you want to use GET for getting response from server just you can try in following method
//just give your URL instead of my URL
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER.If you do this clearly you can get the correct results.
//After that it depends upon the json format whether it is DICTIONARY or ARRAY
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[[jsonArray objectForKey:#"search_api"]objectForKey:#"result"];
I very much doubt that you should send this parameter as a HEADER field.
I also would think that you should be sending a POST and not a GET.
Setting jsonReturn to [[NSMutableArray alloc] init] is nonsense. Explain to yourself why you are doing it instead of setting jsonReturn to nil
Logging the jsonReturn is nonsense, because all the interesting stuff has disappeared. You should log the response and the data that was returned, at least if jsonReturn = nil.
You seem to be confused between GET and POST. You are doing a GET, but supplying data like a POST (usually does, though it isn't mandated, or precluded to use the body data for a GET).
Generally, you don't want to use body data for a GET, it isn't usual / expected so any number of different issues could be occurring. Either change setHTTPMethod: to #"POST" so you are doing a POST properly, or change the parameters to be part of the request URL.
It really all depends what the server expects (and can handle). This is what you need to know and match against...
Subsequently you have a different issue. The param string you supply has characters in it that need to be encoded (like spaces). Use stringByAddingPercentEscapesUsingEncoding: on the param string before you send it to escape these characters.
It works in a browser because it is adding the escape characters for you (which you should see in the browser address bar after it has loaded the response).
i found my issue:
sending paramString Using "Get" Method, cannot send parameters with space between letters.. example: "tel aviv" should be "tel%20aviv"
by adding the following code line:
**urlParam = [urlParam
stringByReplacingOccurrencesOfString:#" " withString:#"%20"];**
fix code:
+ (id)sendParam:(NSString*)ParamString url:(NSString*)url{
NSString* urlParam = [NSString stringWithFormat:#"%#%#",url,ParamString];
urlParam = [urlParam
stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlParam]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSURLResponse *response;
NSError *error;
NSData *aData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"aData=%#",aData);
if (aData) {
jsonReturn=(NSMutableArray*)[NSJSONSerialization JSONObjectWithData:aData options:kNilOptions error:&error];
NSLog(#"jsonReturn %#",jsonReturn);
}
thank you all !

NSURLConnection closes early on GET

I'm working on a method to centralize my URL connections for sending and receiving JSON data from a server. It works with POST, but not GET. I'm using a Google App Engine server and on my computer it'll handle the POST requests and return proper results (and log appropriately), but I get the following error when I try the request with a GET method:
Error Domain=kCFErrorDomainCFNetwork Code=303 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 303.)" UserInfo=0xd57e400 {NSErrorFailingURLKey=http://localhost:8080/api/login, NSErrorFailingURLStringKey=http://localhost:8080/api/login}
In addition, the GAE dev server shows a "broken pipe" error, indicating that the client closed the connection before the server was finished sending all data.
Here's the method:
/* Connects to a given URL and sends JSON data via HTTP request and returns the result of the request as a dict */
- (id) sendRequestToModule:(NSString*) module ofType:(NSString*) type function:(NSString*) func params:(NSDictionary*) params {
NSString *str_params = [NSDictionary dictionaryWithObjectsAndKeys:func, #"function", params, #"params", nil];
NSString *str_url = [NSString stringWithFormat:#"%#%#", lds_url, module];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str_url]];
NSData *data = [[NSString stringWithFormat:#"action=%#", [str_params JSONString]] dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:type];
[request setHTTPBody:data];
[request setValue:[NSString stringWithFormat:#"%d", [data length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Error: %#", error);
NSLog(#"Result: %#", [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]);
return [result objectFromJSONData];
}
A sample call would be:
NSDictionary *response = [fetcher sendRequestToModule:#"login" ofType:#"GET" function:#"validate_email" params:dict];
Again, this works with a POST but not a GET. How can I fix this?
In my case i was not calling [request setHTTPMethod: #"POST" ]
I think the root cause is you have an invalid URL.
JSON encoding will include things like '{', '}', '[' and ']'. All of these need to be URL encoded before being added to a URL.
NSString *query = [NSString stringWithFormat:#"?action=%#", [str_params JSONString]];
query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#", str_url, query]];
To directly answer your question:
According to CFNetwork Error Codes Reference the error is kCFErrorHTTPParseFailure. This means the client failed to correctly parse the HTTP response.
The reason why is that a GET doesn't include a body. Why would you want to submit JSON in a GET anyways?
If the target api returns data only you pass it in the url params.
If you want to send data and "get" a response use a post and examine the body on return.
Sample Post:
NSError *error;
NSString *urlString = [[NSString alloc] initWithFormat:#"http://%#:%#/XXXX/MVC Controller Method/%#",self.ServerName, self.Port, sessionId ];
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
// hydrate the remote object
NSString *returnString = [rdc JSONRepresentation];
NSData *s10 = [returnString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:s10];
NSURLResponse *theResponse = [[NSURLResponse alloc] init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&error];
NSString *message = [[NSString alloc] initWithFormat: #"nothing"];
if (error) {
message = [[NSString alloc] initWithFormat:#"Error: %#", error];
} else {
message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
NSLog(#"%#", message);
return message;

connection failed : Bad Url (null) error while sending POST data from Xcode to classic ASP page.

In my iphone project, I need to pass member Id and pwd to a web server. I have tried my code with Synchronous as well as asynchronous request but I always get error : connection failed: Bad URL (null). can any one please help me to find what's wrong with the code?
My code:
NSString *post =[NSString stringWithFormat:#"memberId=%#&pwd=%#",txtUName.text,txtPwd.text];
NSLog(#"%#",post);
NSURL *url = [NSURL
URLWithString:#"http://testweb.talkfusion.com/videocenter/xlogin.asp%#"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
//set up the request to the website
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[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);
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
The %# at the end in your url is wrong. POST-data are not part of the url.

JSON for Objective-C returns error "Illegal start of token [r]"

I am attempting to connect to a web page and return a JSON string. This string simply needs to be parsed in JSON and returned into an NSArray that I have waiting for it. The problem is that JSON doesn't always return the results. Sometimes, it works well. Sometimes, it returns (null), citing the error below.
self.accounts = nil; // Clear the NSArray
NSString *post = [NSString stringWithFormat:#"username=%#", username.text];
NSData *postData = [NSData dataWithBytes: [post UTF8String] length: [post length]];
// Submit login data
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString: #"http://###.#####.###/app/getaccts.php"]];
[request setHTTPMethod: #"POST"];
[request setValue: #"application/x-www-form-urlencoded" forHTTPHeaderField: #"Content-Type"];
[request setHTTPBody: postData];
// Retreive server response
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
accounts = [[content JSONValue] allValues]; // Parse JSON string into the array
NSLog(#"Array: %#", accounts);
The page I am submitting to returns this:
{"1":"856069060", "2":"856056407"}
JSON logs the following error:
-JSONValue failed. Error is: Illegal start of token [r]
Can I get a little more info ... specifically, I'd like you to check the return value of your sendSynchronousRequest so can you make this change and rerun your test:
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
if (returnData == nil) {
NSLog(#"ERROR: %#", err);
} else {
NSLog(#"DATA: %#", returnData);
}