Objective C "Bad URL" error - objective-c

I am trying to set up an Http GET request to a certain URL from my Objective C code. No matter what I do, or which URL I use, I get the following error:
Connection Failed: Error Domain=NSURLErrorDomain
Code=-1000 "bad URL" UserInfo=0x755c440
{NSUnderlyingError=0x7561950 "bad URL", NSLocalizedDescription=bad URL}
I am new to iOS development, so I am not sure if I am doing this right. I have followed the apple documentation and looked for answers in various forums and even then I get this error.
Here is my code:
NSString *url = [NSString stringWithFormat: #"http://example.com/api/%#/%#", str1, str2];
NSString *encodedUrl = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSLog(#"URL - %#", encodedUrl); // Checking the url
NSMutableURLRequest *theRequest= [[NSMutableURLRequest alloc] init];
[theRequest setHTTPMethod:#"GET"];
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
Any suggestion is most welcome.

You're not initializing your theRequest.
This line does nothing if you're not assigning its return value to a variable.
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
This is the code you should use:
NSString *url = [NSString stringWithFormat: #"http://example.com/api/%#/%#", str1, str2];
NSString *encodedUrl = [url stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSLog(#"URL - %#", encodedUrl); // Checking the url
NSMutableURLRequest *theRequest= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];

Related

How to send Array of objects to JSON?

I am hitting a web service with array of objects. But in server side they are getting only null value for all the fields.
Client side code is:
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:urlRequest
delegate:self];
//************DATA formation
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc]init];
NSMutableDictionary *jsonDict1 = [[NSMutableDictionary alloc]init];
[jsonDict setObject:#"3" forKey:#"rollNo"];
[jsonDict setObject:#"Ezhil" forKey:#"FirstName"];
[jsonDict setObject:#"Arasu" forKey:#"LastName"];
[jsonDict1 setObject:#"4" forKey:#"rollNo"];
[jsonDict1 setObject:#"XYZ" forKey:#"FirstName"];
[jsonDict1 setObject:#"ABC" forKey:#"LastName"];
NSArray *jsonArray=[[NSArray alloc]initWithObjects:jsonDict,jsonDict1, nil];
//Converting to JSON string.
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString *jsonString = [writer stringWithObject:jsonArray];
NSLog(#"JSON String : %#",jsonString);
//************Setting DATA in URL
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[connection start];
// Code for response....
I dont know were i went wrong. Can any one help me for this issue.
Thanks in advance.
I'd scrap the SBJson stuff and just use the native controls...
Do everything the same as you are doing but remove the SBJsonWriter stuff and do this to set the body of the request...
[urlRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:&error]];
That should work.
Thank you.. Application is working fine without any modification. The problem is with server side. But i think we can go with your suggestion instead of using external framework.
In both the case I am getting the json object like this,
JSON String :
[{"rollNo":"3","FirstName":"Ezhil","LastName":"Arasu"},
{"rollNo":"4","FirstName":"XYZ","LastName":"ABC"}]

Reddit API ios modhash/cookie issue

Im' trying to submit to Reddit via my iOS app. I can login fine and am sent back a modhash and a cookie which I save via NSUserDefaults.
The issue is when I post the data I keep getting "USER_REQUIRED" as the response, even though I have included the modhash in the post and set my session cookie. I have even included the following in my app delegate:
[[NSHTTPCookieStorage sharedHTTPCookieStorage]
setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
But it still doesn't work. Here is my code:
-(void) post {
NSString *modhash2 = [[NSUserDefaults standardUserDefaults]
objectForKey:#"modhash"];
NSString *urlString = [NSString
stringWithFormat:#"https://ssl.reddit.com/api/submit"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSString *contentType = [NSString stringWithFormat:#"application/x-www-form-urlencoded;"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request addValue:redditCookie forHTTPHeaderField:#"Cookie"];
[request setHTTPMethod:#"POST"];
NSString *httpBody = [NSString stringWithFormat
:#" ?uh=%#&kind=link&url=%#&sr=%#&title=%#&r=%#&api_type=json",
modhash2,
#"www.google.com",
#"test",
#"Google.com",
#"test"];
[request setHTTPBody:[httpBody dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse* response;
NSError* error = nil;
NSData* result = [NSURLConnection
sendSynchronousRequest:request
returningResponse:&response
error:&error];
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:result
options:NSJSONReadingMutableContainers
error:nil];
NSDictionary *responseJSON = [json valueForKey:#"json"];
NSLog(#"RETURN: %#",responseJSON);
}
Any ideas?

Posting an url i"m getting Invalid request

What would be the reason for getting Invalid Request when we are posting an URL to server in iOS SDK. the URL what i am sending is correct and the data what I'm posting is also correct.
I tried in RestClient also even though I'm getting same error Invalid Request in that also.
Can any one help me what would be the reason for it.
Thanks in advance.
- (NSURLConnection *) executeAsyncHttpPost :(NSString *) baseURL :(NSString *) method
:(id) jsonParams :(int)callerTag
{
NSLog(#"jsonParams: %#", jsonParams);
NSString *urlstr = [NSString stringWithFormat:#"%#", baseURL];
urlstr = [urlstr stringByAppendingFormat:method];
NSLog(#"urlstr: %#", urlstr);
NSString *postLength = [NSString stringWithFormat:#"%d", [jsonParams length]];
NSURL *pUrl = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:pUrl];
NSData *requestData = [[NSData alloc] initWithData:[jsonParams dataUsingEncoding:NSASCIIStringEncoding]];
NSString* myString;
myString = [[NSString alloc] initWithData:requestData encoding:NSASCIIStringEncoding];
NSLog(#"myString: %#", myString);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
self.tag = callerTag;
return [super initWithRequest:request delegate:delegateResponder];
}
The JSON you are posting might be invalid. Please validate it using this. There should be no character outside the { }.
Just post the following string instead of the current JSON
EDIT:
{"jsonRequest" :{"methodName":"CheckUserExist","username":"giriraj.vyas#dotsquares‌​.com","password":"233444"}}

GTM OAuth Twitter update error

I'm having a posting issue with the gtm oauth toolbox. I've been trying to send a tweet to twitter but I keep getting authorization errors. Right now I'm receiving the following error with the code below "POST error: Error Domain=com.google.HTTPStatus Code=401 "The operation couldn’t be completed. (com.google.HTTPStatus error 401.)"
NSString *body = [NSString stringWithFormat: #"status=thisisatest"];
NSString *urlStr = #"http://api.twitter.com/1/statuses/update.json";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];
GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher
fetcherWithRequest:request];
[myFetcher setAuthorizer: mAuth];
[myFetcher beginFetchWithCompletionHandler:^(NSData *retrievedData,
NSError *error)
{
if (error != nil)
{
NSLog(#"POST error: %#", error);
}
else
{
NSDictionary *results = [[[[NSString alloc] initWithData:
retrievedData encoding:NSUTF8StringEncoding] autorelease] JSONValue];
NSLog(#"POST Successful: #%# # %#", [results objectForKey:
#"id"], [results objectForKey: #"created_at"]);
}
}];
What am I doing wrong here? The token is already stored in the keychain. Do I need to retrieve the keychain token or does gtm sign the request automatically?
Ok, I found out the issue. I missed a place in one of the GTM .m files for the consumer key. That's what I get for rushing things. :-)

xml post as parameter for Objective C

How does one post xml as parameter with Objective C?
I've sent a username and a password in xml to the server. I've tried using ASIFormDataRequest. I've posted xml and the server've given the error that is "username or password is false". I think the server doesn't parse the posting xml. Is there any way to post xml as parameter?
NSURL *url = [NSURL URLWithString:#"url code"];
ASIFormDataRequest *request1 =[ASIFormDataRequest requestWithURL:url];
[request1 setPostValue:"xml block" forKey:#"data"];
[request1 addRequestHeader:#"Content-Type" value:#"application/xml;"];
[request1 setDelegate:self];
[request1 startSynchronous];
Yes, it is. Look at my example:
NSString *message = [[NSString alloc] initWithFormat:#"<?xml version=\"1.0\" ?>\n<parameters></parameters>"];
url = [NSURL URLWithString:#"https://https_url.com"];
request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d",[message length]];
[request addValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
[message release];