unsupported URL error code -1002 - ios

Hi Please help me how to prepare NSMutableURLRequest for below api
URL : www.XXXXXXXX.com/api.php
For Login :-
www.XXXXXXXXXXXX.com/api.php?task=login
POST Data :-
"email" => User's email
"pw" => User's Password
json response: session id on successful login
Am trying like this.
NSMutableURLRequest *request;
request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"www.XXXXXXXX.com/api.php?task=login"]];
[request setHTTPMethod:#"POST"];
NSString *postString =#"email=xxxxxxxx#gmail.com&pw=1234";
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];

One reason could be that you forgot to add the "http:" scheme:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.XXXXXXXX.com/api.php?task=login]];
HERE --^
Note also that the correct way to set body data and in particular the length is
NSString *postString =#"email=xxxxxxxx#gmail.com&pw=1234";
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:postData];
because the length of the UTF-8 encoded data can be different from the (Unicode) string length.

I ran into this error when I specified my base URL with a variable that accidentally contained a new line.

Try this:
NSError *error;
NSString *jsonString;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonData1
options:0 error:&error];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSData *postData = [[[NSString alloc] initWithFormat:#"method=methodName&email=%#&password=%#", user_name, pass_word] dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%ld",[postData length]];
jsonData=[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Accept\""];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Content-Type\""];
[request setValue:postLength forHTTPHeaderField:#"\"Content-Length\""];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSError *requestError = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
if ([response statusCode] >= 200 && [response statusCode] < 300) {
NSError *serializeError = nil;
NSString* newStr = [NSString stringWithUTF8String:[urlData bytes]];
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments
error:&serializeError];
NSLog(#"recdata %#",jsonData);
}
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
NSLog(#"theConnection is succesful");
}
[connection start];

Related

How to make json post request?

I have to make json post request with the following request parameters,
{
"method":"login",
"data":{
"username":"korea",
"password":"123456"
}
}
I use the following code to make the request,
NSString *jsonRequest = [NSString stringWithFormat:#"{""\"\method:\"\login\"\"\,""\data:\"{\"\"username\":\"%#\",\"password\":\"%#\"}",username,password];
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http://myurl..."];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
I have to get the response but Im not be able to get the response
Try this
NSDictionary *objectDic = #{#"username" : username, #"password" : password};
NSDictionary *dataDic = #{#"data" : objectDic};
NSDictionary *methodDic = #{#"method" : #"login", #"data": dataDic};
NSData *requestData = [NSJSONSerialization dataWithJSONObject:methodDic
options:NSJSONWritingPrettyPrinted
error:nil];
[request setHTTPBody: requestData];

Create and send JSON data to server using Objective C

I'm trying to send JSON data to server side using POST method, but my code gives null JSON value. I am using Objective C where I fetch data from textField and convert it into string, but after that while converting this value to JSON object, it gives null value. Don't know what to do.
Here is my code:
- (IBAction)loginAction:(UIButton *)sender
{
NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#" ,self.userNameField.text,self.passwordField.text];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
postData = [postData subdataWithRange:NSMakeRange(0, [postData length] - 1)];
NSData*jsonData = [NSJSONSerialization JSONObjectWithData:postData options:NSJSONReadingMutableContainers error:nil];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login/post"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
-(void)MessagePost{
NSString * post =[NSString stringWithFormat:#"http://url.com/clients/project_id=%#&user_id=58&question=%#&send_enquiry=Send",[[self.recordchat objectForKey:#"id"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[_txtfield text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",post);
NSData *postdata= [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength=[NSString stringWithFormat:#"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:post]];
[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;
postdata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnstring=[[NSString alloc]initWithData:postdata encoding:NSUTF8StringEncoding];
NSLog(#"String : %#",returnstring);
if (postdata){
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:postdata options:NSJSONReadingMutableContainers error:nil];
NSDictionary* latestLoans = [dict objectForKey:#"status"];
NSLog(#"Status dict = %#",latestLoans);
} else{ NSLog(#"Error while posting messages.");}}
instead of writing NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#" ,self.userNameField.text,self.passwordField.text];
you should use this
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:#"Username"];
[post setValue:self.passwordField.text forKey:#"Password"];
Try this -
- (IBAction)loginAction:(UIButton *)sender
{
NSDictionary *dictDetails = #{
#"Username" : self.userNameField.text,
#"Password" : self.passwordField.text
};
NSString *jsonRequest = [dict JSONRepresentation];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login/post"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: requestData];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)
[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
Finally I wrote the correct code and it's working fine now. Please suggest me If any further modification is required..
Thank you all for your time and support..
Here is my code:
- (IBAction)loginAction:(UIButton *)sender
{
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:#"username"];
[post setValue:self.passwordField.text forKey:#"password"];
NSArray* notifications = [NSArray arrayWithObjects:post, nil];
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:kNilOptions error:&writeError];
NSString *postLength = [NSString stringWithFormat:#"%d",[jsonData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSLog(#"JSON Summary: %#", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response Error= %#", response);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSData *responseData = [[NSData alloc]initWithData:urlData];
NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Random Output= %#", jsonObject);
[self performSegueWithIdentifier:#"DASHBOARDSEGUE" sender:sender];
}else {
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}

How to send raw data to API

I have one text field I need to send two data's to API.
NSString *post =[NSString stringWithFormat:#"val1=%#,val2=%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"val1"],val2];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://api.test.com/send"]];
[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 *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"log%#",str);
}
I need to send only raw data to API this is my code.Please check and let me know thanks
NSData *postData = [someStringToPost dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:someURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
if (error)
{
//error
}
else
{
//no error
}
Try this
Have you tried converting it to NSData and sending that?
Here's the conversion:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
That will give you the data in bytes, then just pass it in with the normal networking function calls.

iOS 5 Json Serialization

I have used JSON Serialization to get json response, here i'mn getting all fine, but when i need to post some values as key value pair with the URL. I have done like this, but didn't get the result.
NSArray *objects = [NSArray arrayWithObjects:#"uname", #"pwd", #"req",nil];
NSArray *keys = [NSArray arrayWithObjects:#"ann", #"ann", #"login", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:keys forKeys:objects];
if ([NSJSONSerialization isValidJSONObject:dict]) {
NSError *error;
result = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (error == nil && result != nil) {
// NSLog(#"Success");
}
}
NSURL * url =[NSURL URLWithString:#"URL_address_VALUE/index.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d",[result length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:result];
NSURLResponse *res = nil;
NSError *error = nil;
NSData *ans = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:&error];
if (error == nil) {
NSString *strData = [[NSString alloc]initWithData:ans encoding:NSUTF8StringEncoding];
NSLog(#"%#",strData);
}
I don't know what goes wrong here... Please dudes help me..
There are multiple Errors in your Code, Use my Code as a Reference and compare it to yours and you'll get the Errors done by you.
The Below code is working correctly from the Point of View of Objective-C. There are some Errors regarding your URL or Service Side.
Working Code :
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"ann",#"uname",#"ann",#"pwd",#"login",#"req", nil];
NSLog(#"dict :: %#",dict);
NSError *error2;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error2];
NSString *post = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"postLength :: %#",postLength);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://exemplarr-itsolutions.com/dbook/index.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error3;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error3];
NSString *str = [[NSString alloc] initWithData:POSTReply encoding:NSUTF8StringEncoding];
NSLog(#"str :: %#",str);

send JSON Object Request to Server

Iam sending JSON Object request to the server but server returns Status Code 405. how to solve this problem. please any one help me.
My code :
+(NSData *)GpBySalesDetailed:(NSMutableDictionary *)spDetailedDict{
NSLog(#"spDetailedDict:%#",spDetailedDict);
NSString *dataString = [spDetailedDict JSONRepresentation];
NSLog(#"%#dataString",dataString);
return [dataString dataUsingEncoding:NSUTF8StringEncoding];
}
-(void)requestWithUrl:(NSURL *)url WithJsonData:(NSData *)JsonData
{
NSMutableURLRequest *urlRequest=[[NSMutableURLRequest alloc]initWithURL:#"http://srbisolutions.com/SmartReportService.svc/GpBySalesPersonDetailed];
if (JsonData != nil) {
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:JsonData];
}
else
{
[urlRequest setHTTPMethod:#"GET"];
}
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
[conn start];
}
HTTP Code 405 means "Method not allowed", it does not accept a post request for this particular URI. Either the server must be configured to accept POST requests or it should offer another URI.
try this
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:YOURURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0 ];
NSLog(#"final request is %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//Here postData is a Dictionary with key values in web services format use ur own dic
[request setHTTPBody:[[self convertToJSON:postData] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *contentLength = [NSString stringWithFormat:#"%d",[[request HTTPBody] length]];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
self.responseData = [NSMutableData data];
}
//============JSON CONVERSION========
-(NSString *)convertToJSON:(id)requestParameters
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestParameters options:NSJSONWritingPrettyPrinted error:nil];
NSLog(#"JSON DATA LENGTH = %d", [jsonData length]);
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON STR LENGTH = %d", [jsonString length]);
return jsonString;
}
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"yourURL"]];
[theRequest setHTTPMethod:#"POST"];
NSDictionary *jsonRequest =
[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#//add your objects
]
forKeys:[NSArray arrayWithObjects:
title,
link,
nil]];
NString *jsonBody = [jsonRequest JSONRepresentation];
NSLog(#"The request is %#",jsonBody);
NSData *bodyData = [jsonBody dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:bodyData];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// create the connection with the request
// and start loading the data
theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

Resources