In my app I've to read xml data from a server. To access to this server it's necessary to give an username and a password, how I can solve that?
I tried to read xml data with this code:
-(id)sendRequestToURL:(NSString*)url withMethod:(NSString*)method {
NSURL *finalUrl;
if ([method isEqualToString:#"GET"]) {
finalUrl = [NSURL URLWithString:url];
} else {
NSLog(#"Metodo non implementato");
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalUrl];
[request setHTTPMethod:method];
[request setValue:#"x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-type"];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
[connection start];
}
return connection;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Ho ricevuto una risposta");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"Ho ricevuto dei dati: %#", data);
NSMutableData *test = [[NSMutableData alloc]init];
[test appendData:data];
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", string);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Ho terminato di caricare");
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"%#", error);
}
It connect correctly but if I try to read what's the problem I'm getting this HTML:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Authorization Required</title>
</head><body>
<h1>Authorization Required</h1>
<p>This server could not verify that you
are authorized to access the document
requested. Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
<hr>
<address>Apache/2.2.15 (Red Hat) Server at 54.204.6.246 Port 80</address>
</body></html>
So I guess that it's necessary to give username and password but how I can do that?
base64EncodedString Set the authentication header field:
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"myusername", #"mypassword"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedString]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
To convert NSData to base64 String you need NSData+Base64.h
I solved the issue in this way:
NSString *address = [NSString stringWithFormat:#"http://54.204.6.246/magento8/api/rest/products/?category_id=3"];
[self sendRequestToURL:address withMethod:#"GET"];
-(id)sendRequestToURL:(NSString*)url withMethod:(NSString*)method {
NSURL *finalUrl;
if ([method isEqualToString:#"GET"]) {
finalUrl = [NSURL URLWithString:url];
} else {
NSLog(#"Metodo non previsto");
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalUrl];
[request setHTTPMethod:method];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"user", #"password"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedString]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setValue:#"x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-type"];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
[connection start];
}
return connection;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Ho ricevuto una risposta");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"Ho ricevuto dei dati: %#", data);
jsonCategory = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Ho terminato di caricare");
JsonCategoryReader *reader = [[JsonCategoryReader alloc]init];
[reader parseJson:jsonCategory];
}
I hope it's useful for other people who has the same problem. (watch out the code it's just a snipped and probably there aren't all the {})
Related
Little issue that's been bothering me. I've been making a POST request to my AWS RDB. The request should return a json output. The issue I'm having is that I'll receive bytes back, but sometimes it contains incomplete json, thus converting it to a dictionary won't work. Sometimes I also receive a null value for the nsdata received, but I can print out the length of the data. Any ideas? Here's my iOS code for requests:
#import "ServiceConnector.h"
#implementation ServiceConnector{
NSMutableData *receivedData;
}
-(void)getTest{
//Send to server
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY_WEBSITE"]];
[request setHTTPMethod:#"GET"];
//initialize an NSURLConnection with the request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(!connection){
NSLog(#"Connection Failed");
}
}
-(void)postTest:(NSMutableArray *)carSearches{
//build up the request that is to be sent to the server
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MY_WEBSITE"]];
[request setHTTPMethod:#"POST"];
NSError *writeError = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:carSearches options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON Output: %#", jsonString);
[request setHTTPBody:data]; //set the data as the post body
[request addValue:[NSString stringWithFormat:#"%lu",(unsigned long)data.length] forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(!connection){
NSLog(#"Connection Failed");
}
}
#pragma mark - Data connection delegate -
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ // executed when the connection receives data
if(!receivedData){
receivedData = [[NSMutableData alloc]init];
[receivedData appendData:data];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ //executed when the connection fails
NSLog(#"Connection failed with error: %#",error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"Request Complete,recieved %lu bytes of data",(unsigned long)receivedData.length);
NSString *tmp = [NSString stringWithUTF8String:[receivedData bytes]];
NSLog(#"%#",tmp);
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:[receivedData bytes] length:[receivedData length]] options:NSJSONReadingAllowFragments error:&error];
[self.delegate requestReturnedData:dictionary];
}
In this section:
if(!receivedData){
receivedData = [[NSMutableData alloc]init];
[receivedData appendData:data];
}
You are only appending data if the object hasn't been created yet. You want to append every time. That if statement should read like this:
if(!receivedData){
receivedData = [[NSMutableData alloc]init];
}
[receivedData appendData:data];
I have a URL that when typed into a browser (EG Safari) requests a username and password, the response API comes back in the form of JSON.
Now I'm trying to connect to this API in my iOS app so I can work with the JSON data and I'm not sure if I'm going about it the correct way.
NSString *post = [NSString stringWithFormat:#"&Username=%#&Password=%#",#"username",#"password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSString *string = [NSString stringWithFormat:#"jsonURL"];
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(connection)
{
NSLog(#"connection success");
}
else
{
NSLog(#"connection could not be made");
}
The NSLog is coming back with a "connection success" response. However, I can't seem to load the JSON response into an NSDictionary or NSArray. I've used NSJSONSerialization here.
NSMutableData *urlData;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
urlData = [[NSMutableData alloc] init];
NSLog(#"DID RECEIVE RESPONSE %#", urlData);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
[urlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"FINISHED LOADING DATA %#", connection);
NSError *jsonParsingError = nil;
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
if (jsonParsingError) {
NSLog(#"JSON ERROR: %#", [jsonParsingError localizedDescription]);
} else {
NSLog(#"Parsed Object is %#", parsedObject);
}
}
And here is my JSON error from the NSLog: "JSON ERROR: The operation couldn’t be completed. (Cocoa error 3840.)"
Where am I going wrong? Thanks in advance.
NSString *jsonstring = [NSString stringWithFormat:#"{\"userName\":\"%#\",\"password\":\"%#\",\"loginFrom\":\"2\",\"loginIp\":\"%#\"}",[username_text removequotes],[password_text removequotes],ipaddress];//The removeQuotes method is used to escape sequence the " to \" so that the json structure won't break. If the user give " in the username or password field and if we dint handle that the json structure will break and may give an expection.
NSLog(#"the json string we are sending is %#",jsonstring);
NSData *strdata = [json1 dataUsingEncoding:NSUTF8StringEncoding];
NSString *fixedURL =[NSString stringWithFormat:#"%#",loginURL];//the url is saved in loginURL variable.
NSURL *url = [NSURL URLWithString:fixedURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: strdata];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
NSLog(#"Connected to service waiting for response");
}
Example code for login using json web services
Finally resolved this. Use:
-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSLog(#"received authentication challenge");
NSURLCredential *newCredential = [NSURLCredential credentialWithUser:#"username"
password:#"password"
persistence:NSURLCredentialPersistenceForSession];
NSLog(#"credential created");
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
NSLog(#"responded to authentication challenge");
}
else {
NSLog(#"previous authentication failure");
}
}
You actually don't need to set request values (e.g.: [request setValue:postLength forHTTPHeaderField:#"Content-Length"];) etc etc
Connect with a:
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
and handle the JSON response data with:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
urlData = [[NSMutableData alloc] init];
NSLog(#"DID RECEIVE RESPONSE");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
NSLog(#"THE RAW DATA IS %#", data);
[urlData appendData:data];
NSString *strRes = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"LOGGING THE DATA STRING %#", strRes);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"FINISHED LOADING DATA %#", connection);
NSError *jsonParsingError = nil;
//id object = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
NSArray *parsedObject = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
NSLog(#"RESPONSE: %#",[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]);
if (jsonParsingError) {
NSLog(#"JSON ERROR: %#", [jsonParsingError localizedDescription]);
} else {
NSLog(#"PARSED OBJECT %#", parsedObject);
}
}
I suggest use AFNetworking whenever deal with networking.
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:username
password:password];
I have 3 UITextfield and 1 Button, when I button click 3 UITextfield data sent to the database using forms.
my code is send the data to database but it's show in null values in database.
<form action="//http://192.168.3.171:8090/RestWebService/rest/person" id="suggestions" method="post">
<input id="name" name="name" type="text" >
<input id="suggestion" name="suggestion" type="text">
<input id="submitsuggestion" name="submitsuggestion" type="text">
</form>
Viewcontroller.M
#import "ViewController.h"
#interface ViewController ()
{
NSMutableData *recievedData;
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
NSMutableString *first;
}
#end
#implementation ViewController
#synthesize webview;
#synthesize firstName;
#synthesize lastName;
#synthesize email;
- (void)viewDidLoad
{}
- (IBAction)send:(id)sender
{
NSString *name = firstName.text;
NSLog(#" name is %# ",name);
NSString *lastname = lastName.text;
NSLog(#" name is %# ",lastname);
NSString *emailname = email.text;
NSLog(#" name is %# ",emailname);
if (name.length == 0 || lastname.length == 0 || email.text==0) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Message!" message:#"plz enter 3 fields " delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}else{
webData=[NSMutableData data];
NSURL *url = [NSURL URLWithString:#"http://192.168.3.128:8050/RestWebService/rest/person"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [#"name=firstName&suggestion=lastName&submitsuggestion=email" dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"requestData%#",requestData);
[request setHTTPMethod:#"POST"];
[request setValue:#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//[request setValue:requestData forHTTPHeaderField:#"Content-Length"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSLog(#"requestData*******:%#",requestData);
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection successfull");
NSLog(#"GOOD Day My data %#",webData);
}
else
{
NSLog(#"connection could not be made");
}
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
NSLog(#"DidReceiveResponse");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
NSLog(#"DidReceiveData");
NSLog(#"DATA %#",data);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error is");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[webData length]);
NSLog(#"Data is %#",webData);
// NSLog(#"receivedData%#",_receivedData);
NSString *responseText = [[NSString alloc] initWithData:webData encoding: NSASCIIStringEncoding];
NSLog(#"Response: %#", responseText);//holds textfield entered value
NSLog(#"");
NSString *newLineStr = #"\n";
responseText = [responseText stringByReplacingOccurrencesOfString:#"<br />" withString:newLineStr];
NSLog(#"ResponesText %#",responseText);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
my UITextfield data will be stored in database but it's null.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.appListData = [NSMutableData data]; // start off with new data
}
or
How to pass web service
NSString *post = [NSString stringWithFormat:#"first_name=%#&last_name=%#",firstName.text,lastName.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://localhost/promos/index.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
// indicator.hidden = NO;
mutableData = [[NSMutableData alloc]init];
}
your PHP code
<?php
$first name = $_POST['first_name'];
$last name=$_POST['last_name'];
echo $username;
?>
Exact answer here for your above Question[FOR POSTING DATA IN YOUR URL(SERVER)]
//Here YOUR URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://192.168.3.128:8050/RestWebService/rest/person"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString strin gWithFormat:#"user_email=%#&user_login=%#&user_pass=%#& last_upd_by=%#&user_registered=%#&",txtemail.text,txtuser1.text,txtpass1.text,txtuser1.text,datestr,nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
/* ViewController *view =[[ViewController alloc]initWithNibName:#"ViewController" bundle:NULL];
[self presentViewController:view animated:YES completion:nil];*/
}
else
{
NSLog(#"faield to connect");
}
Make life easy on yourself and use AFNetworking. Instructions for how to post form data are here: https://github.com/AFNetworking/AFNetworking
this is the snippet to my Code, i am sending the code to a PHP page, but when i do print_r($_POST); i get empty Array, but when i do print_r($_GET) i get the variable which i am using to post the data i.e name but it also is empty, can any 1 sort out what i am doing wrong here
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnFetchData1:(id)sender {
// NSString *urlString = [NSString stringWithFormat:#"http://localhost/adi/adnan.php?name=%#", [self.txtName text]];
NSString *urlString = [NSString stringWithFormat:#"http://localhost/adi/adnan.php"];
NSString *post = [NSString stringWithFormat:#"name=%#",#"adnan"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
delegate:self];
if (conn) {
_receivedData=[NSMutableData data];
} else {
//something bad happened
}
}
#pragma NSUrlConnectionDelegate Methods
-(void)connection:(NSConnection*)conn didReceiveResponse:(NSURLResponse *)response
{
if (_receivedData == NULL) {
_receivedData = [[NSMutableData alloc] init];
}
[_receivedData setLength:0];
NSLog(#"didReceiveResponse: responseData length:(%d)", _receivedData.length);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error {
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Succeeded! Received %d bytes of data",[_receivedData length]);
NSString *responseText = [[NSString alloc] initWithData:_receivedData encoding: NSASCIIStringEncoding];
NSLog(#"Response: %#", responseText);
NSString *newLineStr = #"\n";
responseText = [responseText stringByReplacingOccurrencesOfString:#"<br />" withString:newLineStr];
[self.lblData setText:responseText];
}
You created postLength but never used it, try this it might solve it:
//create URL for the request
NSString *urlString = [NSString stringWithFormat:#"http://localhost/adi/adnan.php"];
//Post data
NSString *post = [NSString stringWithFormat:#"name=%#",#"adnan"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding]
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
//the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//Bind the request with Post data
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
I want to use http Get and Post for getting the request and response of certain URL request,
But i dont know how to use them in objective c..
and Which one will come first Get or Post in establishment of connection.?
how to modify the content and post them back to the server..
Can any one please help me?
for get use :
+(NSMutableURLRequest*)getURq_getansascreen:(NSString*)ws_name {
NSLog(#"%#",ws_name);
NSMutableURLRequest *urlReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:ws_name] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[urlReq addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[urlReq setHTTPMethod:#"GET"];
return urlReq;
}
for post use :
+(NSMutableURLRequest*)postURq_getansascreen:(NSString*)ws_name :(NSString*)service {
NSString *tempUrl = domainURL;
NSString *msgLength = [NSString stringWithFormat:#"%d",[ws_name length]];
NSMutableURLRequest *urlReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#Service=%#",tempUrl,service]] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[urlReq addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlReq addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[urlReq setHTTPMethod:#"POST"];
[urlReq setHTTPBody: [ws_name dataUsingEncoding:NSUTF8StringEncoding]];
return urlReq;
}
//Call this in view did load as `
WSPContinuous *wspcontinuous = [[WSPContinuous alloc] initWithRequestForThread:[webService getURq_getansascreen:[webService GetDetails:str_filter]] sel:#selector(WS_GetDetailsLoaded:) andHandler:self];`
//create class WSPContinuous and add these fns..
-(id)initWithRequestForThread:(NSMutableURLRequest*)urlRequest sel:(SEL)seletor andHandler:(NSObject*)handler {
if (self=[super init]) {
self.MainHandler = handler;
self.targetSelector = seletor;
self.urlReq = urlRequest;
[self performSelectorOnMainThread:#selector(startParse) withObject:nil waitUntilDone:NO];
}
return (id)urlReq;
}
-(void)startParse{
NSLog(#"URL CALLING %#",urlReq.URL);
con = [[NSURLConnection alloc] initWithRequest:urlReq delegate:self];
if (con) {
myWebData = [[NSMutableData data] retain];
NSLog(#"myWebData old....%#",myWebData);
}
else {
[self.MainHandler performSelectorOnMainThread:targetSelector withObject:nil waitUntilDone:NO];
}
}
//-------------------------------connection-----------------
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[myWebData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[myWebData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[self.MainHandler performSelectorOnMainThread:targetSelector withObject:nil waitUntilDone:NO];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *thexml = [[NSString alloc] initWithBytes:[myWebData mutableBytes] length:[myWebData length] encoding:NSUTF8StringEncoding];
NSLog(#"xmlDictionary %#",thexml);
[thexml release];
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLData:myWebData error:&parseError];
[AlertHandler hideAlert];
[MainHandler performSelector:targetSelector withObject:xmlDictionary];
}
If you want to start, a better idea would be to do some reading on NSMutableURLRequest and related topics like NSURLConnection.
You get sample code everywhere. Just google it.
Google search -> objective c get and post
and First hit -> Tutorials for using HTTP POST and GET on the iPhone in Objective-C