error while making URL request iPhone - iphone

I asked a question and followed following way(suggested by Jaybit):
Pass username and password in URL for authentication
Now, I'm getting this error(stack track):
2013-02-12 11:56:11.734 Calendar[4074:c07] didReceiveData
2013-02-12 11:56:19.519 Calendar[4074:c07] receivedString:<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
at System.Xml.XmlReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
--- End of inner exception stack trace ---</soap:Text></soap:Reason><soap:Detail /> </soap:Fault></soap:Body></soap:Envelope>
(lldb)
Here is my code:
- (IBAction)btnLoginClick:(id)sender
{
//Call Calendar View
if(self.viewController == nil) {
CalendarViewController *detailView = [[CalendarViewController alloc] initWithNibName:#"CalendarViewController" bundle:nil];
self.viewController = detailView;
}
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?"]];
NSString *postString = [NSString stringWithFormat:#"username=%#&password=%#",userName, passWord];
NSLog(#"%#",userName);
NSLog(#"%#",passWord);
NSData *postData = [NSData dataWithBytes: [postString UTF8String] length: [postString length]];
//URL Requst Object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:600];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: postData];
appConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.appConnection start];
//tryed with Async...
/* NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}];*/
[self.navigationController pushViewController:self.viewController animated:YES];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
tempdata = data;
NSLog(#"didReceiveData");
if (!self.receivedData){
self.receivedData = [NSMutableData data];
}
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading");
NSString *receivedString = [[NSString alloc] initWithData:tempdata encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}
please help.thank.

I've worked with requesting a soap URL before, the following code worked for me:
NSString *soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
"<soap:Body>\n"
"<YourServiceName xmlns=\"http://tempuri.org/\">\n"
"<username>%#</username>\n"
"<passowrd>%#</passowrd>\n"
"</YourServiceName>\n"
"</soap:Body>\n"
"</soap:Envelope>\n", userName, passWord
];
NSURL *url = [NSURL URLWithString:#"http://URL/service1.asmx"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: [NSString stringWithFormat:#"http://tempuri.org/%#",service] forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest setTimeoutInterval:10];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
responseData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}

Related

How to pass parameter in php webservice?

I am working in an app in which i need to pass the json object in that parameter of the request string, now I am stuck here and have no idea how to do this.
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [NSMutableData data] ;
NSString *service = #"http://localhost.abc.com/index.php?p=api/user/register";
NSString *requestString = [NSString stringWithFormat:#"{\"Name\":\"%#\",\"Email\":\"%#\",\"Password\":\"%#\",\"PasswordMatch\":\"%#\",\"TermsOfUSe\":\"1\"}",txtusername.text,txtemail.text,txtpassword.text,txtretypepassword.text];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *urlLoc=#"";
urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL:- %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:requestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSLog(#"%#",request);
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [NSMutableData data] ;
NSString *service = #"http://localhost.abc.com/index.php?p=api/user/register";
NSString *requestString = [NSString stringWithFormat:#"{\"Name\":\"%#\",\"Email\":\"%#\",\"Password\":\"%#\",\"PasswordMatch\":\"%#\",\"TermsOfUSe\":\"1\"}",txtusername.text,txtemail.text,txtpassword.text,txtretypepassword.text];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *urlLoc=#"";
urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL:- %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:requestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSLog(#"%#",request);
Delegate method of Connection
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
//**check here for responseData & also data**
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:#"Connection failed: %#", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
//do something with the json that comes back ... (the fun part)
}
/ /// / ///////// EDITED Answer /////////////////////
GET Method: In this method you can append the request data behind the web- service.As you doing now by line [request setHTTPMethod: #"POST"];.
POST Method: In this method, you can't append the requested data. But pass the dictionary as a parameter. Like below:
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:#"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:#"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:#"nick_name", #"UDID", #"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:#"question"];
NSString *jsonRequest = [jsonDict JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
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 alloc]initWithRequest:request delegate:self];

how to write data on server?

i am making a registration page were user can register?
this is my code..............
-(IBAction)btn_log:(id)sender
{
//NSString* username = nameInput.text;
//NSString* pass = passInput.text;
NSString* firstname = nameInput.text;
NSString* lastname = passInput.text;
NSString* bname = lastInput.text;
NSString *post =
[[NSString alloc] initWithFormat:#"fname=%#&lname=%#&email=%#",firstname,lastname,bname];
//NSString *post = [[NSString alloc]initWithFormat:#"fname=firstname&lname=lastname&email=bname];
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest * request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.yoursite.com/file.php"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) NSLog(#"Connection Successful");
}
But it's not working so please can anyone suggest me where i am making mistake.
try in this way may be it will help you
Nsurl *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.yoursite.com/file.php"]]];
nsstring *body = [nsstring stringwithformat:#"%#,%#",nameinput,paasinput];
nsmutableurlrequest *request = [nsmutablerequest alloc]initwithurl:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request sethttpbody:[body dataysubgebcidubg:asciiiencoding allowlossyconversion : true]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) NSLog(#"Connection Successful");
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Replace above line of your code with following line. Probably it will work.
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

soap web service parsing

i am trying to parse soap web service for authentication and following is the code
currentElement = [[NSString alloc] init];
NSString* email=[NSString stringWithFormat:#"sbhushan#gmail.com"];
NSString* password=[NSString stringWithFormat:#"5Pb&Q?4t"];
NSString* soapMesasge=[NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<Authentication xmlns=\"http://tempuri.org/\">"
"<userId>%#</userId>"
"<password>%#</password>"
"</Authentication>"
"</soap:Body>"
"</soap:Envelope>",email,password];
NSURL* url=[NSURL URLWithString:#"http://codeexsolutions.com/HosService/ServiceHOSProvider.asmx"];
NSMutableURLRequest* theRequest=[NSMutableURLRequest requestWithURL:url];
NSString* msgLength=[NSString stringWithFormat:#"%d",[soapMesasge length]];
[theRequest addValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue:#"http://tempuri.org/Authentication" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:[soapMesasge dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection)
{
webData =[[NSMutableData alloc]retain];
}
else
{
// Inform the user that the connection failed.
}
and imlemented all the delegate method of parsing but do not getting call in
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
or not getting any data please help
hi Friend
your method looks OK dont know why not working , u see any data on consol?? try this or take a look on webservices may be data not come from there
NSString *soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><GetClientData xmlns=\"http://tempuri.org/\"><pSearch>%#</pSearch></GetClientData></soap:Body></soap:Envelope>\n", nameInput.text];
NSURL *url = [NSURL URLWithString:#"http://192.168.1.162/iphone/service.asmx"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/GetClientData" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}

XML parsing is not working as expected in Objective-C

I am new to iPhone programming, and this is the first time parsing XML file. I have added the url and also hardcoded the XML file into the string, however I am not getting the correct response from the server.
Here is my code:
NSString *post = #"<?xml version=\"1.0\"encoding=\"UTF-8\"?<request><call>GetNewChapters</call><udid>1000000000000000000000000000000000000000</udid><book_id>1</book_id><updatetoken>B20100125054802</updatetoken></request>";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url=[NSURL URLWithString:#"https://www.paisible.com/babelle_api"];
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];
NSString *myStr = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"String Value :%#",myStr);
NSLog(#"theRequest: %#", request);
NSURL *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}
Where as webdata is NSMutable data. Please let me know what errors I have made in my parsing code.
Try to replace
NSURL *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
with the following:
NSURLResponse *resp;
NSError *error;
NSMutableData *webData = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&error];
Than, check what "webData" contains.

Just want to confirm if this request is 100% secure connection

I am writing an iPhone App and I need to securely send an XML request and receive it ALL securely. I think I did it right I just want some confirmation that the below code is all secure.
NSURL *url = [NSURL URLWithString: #"https://secure.site.com/request"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [xml length]];
[req addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [xml dataUsingEncoding:NSUTF8StringEncoding]];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn)
webData = [[NSMutableData data] retain];
and in the connectionDidFinishLoading..
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *gotXml = [[NSString alloc]
initWithBytes: [webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
Yes, so long as the URL has https:// in it, the request will be sent securely.