i took this code from a different question and my script file has more inputs, not just mydata, also the data going into the mydata should not be static text, it should be from a NSString.
So my question is, how do i post multiple pieces of data to my script and how would I input a value from a NSString because my understand is i cannot use NSStrings with c data types. not sure if thats the correct terminology so please correct me if i am wrong.
const char *bytes = "mydata=Hello%20World";
NSURL *url = [NSURL URLWithString:#"http://www.mywebsite.com/script.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *responseString = [[NSString alloc] initWithFormat:#"%#", responseData];
NSLog(#"responseData: %#", responseData);
userData = responseData;
New issue using answer below
NSMutableData *data = [NSMutableData data];
NSString *number = numberIB.text;
NSString *name = nameIB.text;
NSString *nameString = [[NSString alloc] initWithFormat:#"name=", name];
NSString *numberString = [[NSString alloc] initWithFormat:#"number=", number];
NSLog(nameString);
NSLog(numberString);
[data appendData:[nameString dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[numberString dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:#"http://www.siteaddress.com/test.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
//[request setHTTPBody:[NSData dataWithBytes:data length:strlen(data)]];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *responseString = [[NSString alloc] initWithFormat:#"%#", responseData];
NSLog(#"responseData: %#", responseData);
the NSLogs for nameString and numberString come back name= and number= without any data. causing no data to be sent to my script.
You can use an NSMutableData object to append bytes as needed, like so:
NSMutableData *data = [NSMutableData data];
const char *bytes = "mydata=Hello%20World";
[data appendBytes:bytes length:strlen(bytes)];
//...
const char *moreBytes = "&someMoreData=Fantastic";
[data appendBytes:moreBytes length:strlen(moreBytes)];
Edit: If you want to append a NSString into the data buffer, you can use -[NSString dataUsingEncoding:] and pass it off to -appendData:
NSString *someString = #"blah";
[data appendData:[someString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:data];
Related
I want ot pass username and password in URL(web service) for user authentication which will return true and false.I'm doing this as following:
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSData *getUserData = [userName dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getUserLength = [NSString stringWithFormat:#"%d",[getUserData length]];
NSData *getPassData = [passWord dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getPassLength = [NSString stringWithFormat:#"%d",[getPassData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://URL/service1.asmx"]];
[request setHTTPMethod:#"GET"];
Now, I wanted to know How can I pass my username and password in this URL to make request.
Could any one please suggest or give some sample code?
Thanks.
Try this :-
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName.text];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword.text];
NSData *getUserData = [userName dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getUserLength = [NSString stringWithFormat:#"%d",[getUserData length]];
NSData *getPassData = [passWord dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getPassLength = [NSString stringWithFormat:#"%d",[getPassData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?%#&%#",userName,passWord]]];
[request setHTTPMethod:#"GET"];
Hope it helps you..
NSString *urlStr = [NSString stringWithFormat:#"http://URL/service1.asmx?%#&%#",userName,passWord];
[request setURL:[NSURL URLWithString:urlStr]];
To improve the secure , you may use the Http Basic Authentication.
There are answer here.
First off I would not pass a username and password across in a url. You should do this using post.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?"]];
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSString *postString = [NSString stringWithFormat:#"username=%#&password=%#",userName, passWord];
NSData *postData = [NSData dataWithBytes: [postString UTF8String] length: [postString length]];
//URL Requst Object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:TIMEOUT];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: postData];
This is more secure then passing sensitive data across in a url.
Edit
To get the response you can check this out. NSURLConnection and AppleDoc NSURLConnection
You can use a few different methods to handle the response from the server.
You can use NSURLConnectionDelegate
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
along with the delegate call backs:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)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:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}
Or you can also use NSURLConnection sendAsynchronousRequest block
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}];
I am having 1 webservice in php which is having browser url mentioned bel :
http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01 01:00:00
Now when I try to fetch url in my iphone app, it is taking this url:
http://Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00
This is creating problem.
i have used this code for fetching data from my url.
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"";
NSString *str;
str = #"LastUpdated";
NSString *requestString = [NSString stringWithFormat:#"{\"LastUpdated\":\"%#\"}",str];
// [[NSUserDefaults standardUserDefaults] setValue:nil forKey:#"WRONGANSWER"];
NSLog(#"request string:%#",requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:#"URL"];
//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];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"Resp : %#",responseString);
if (respError)
{
// NSString *msg = [NSString stringWithFormat:#"Connection failed! Error - %# %#",
// [respError localizedDescription],
// [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ACTEC"
message:#"check your network connection" delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{
......
}
here,i am getting null response as url is getting decoded...How can I make this solved...
Help me out.
Thanks in advance.
NSString *urlLoc = [[fileContents objectForKey:#"URL"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableData *postData = [NSMutableData data];
NSMutableURLRequest *urlRequest;
[postData appendData: [[NSString stringWithFormat: #"add your data which you want to send"] dataUsingEncoding: NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:urlLoc]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSString *temp = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"\n\nurl =%# \n posted data =>%#",urlLoc, temp);
check nslog. that which data u send to service.
NSData *response = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"json_string >> %#",json_string);
Maybe this will help you.
hey dear just for an another example i just post my this code..
first Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00"]];
Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc]
initWithData:response encoding:NSUTF8StringEncoding];
Parse the JSON response into an object Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil]
And in statuses array you have all the data you need.
i hope this help you...
:)
I am trying to implement an Objective C program to interface with activeCollab 3 beta and am having some issues. I can enter the url that the NSLog outputs in the browser and it works just fine pulling the xml for all the projects and it is not wanting to work for me when I try to access it via this program, it is giving me a HTTP 403 error. I am new to Objective C and am doing this as a learning experience so some code may be redundant. Thanks in advance for any help. The import is surrounded in angle brackets but will cause it to be hidden on StackOverflow so I have placed it in quotes
#import "Foundation/Foundation.h"
int main (int argc, const char * argv[]) {
NSString *token = #"my-token";
NSString *path_info = #"projects";
NSString *url = #"http://my-site/api.php?";
NSString *post = [[NSString alloc] initWithFormat:#"path_info=%#&auth_api_token=%#",path_info, token];
NSLog(#"Post: %#", post);
NSString *newRequest;
newRequest = [url stringByAppendingString:post];
NSLog(#"Path: %#", newRequest);
NSData *postData = [newRequest dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
[request setURL:[NSURL URLWithString:newRequest]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *returnData = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"%#", returnData);
//printf("Print line");
return 0;
}
Your request headers are restricting and unnecessary, and for AC API you want a GET request rather than POST
int main (int argc, const char * argv[])
{
NSString *requestString = [[NSString alloc] initWithFormat:#"path_info=%#&auth_api_token=%#", path_info, token];
NSLog(#"Post: %#", requestString);
NSString *newRequest;
newRequest = [url stringByAppendingString: requestString];
NSLog(#"Path: %#", newRequest);
NSData *postData = [newRequest dataUsingEncoding: NSASCIIStringEncoding allowLossyConversion: YES];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSLog(#"Data: %#", postData);
[request setURL: [NSURL URLWithString:newRequest]];
[request setHTTPMethod: #"GET"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &err];
NSString *returnData = [[[NSString alloc] initWithData: responseData encoding: NSUTF8StringEncoding] autorelease];
NSLog(#"Return: %#", returnData);
//printf("Print line");
return 0;
}
I need to parse the data I receive the following way:
[
{
"IdEmpleado":1,
"Nombre":"Cesar",
"Edad":"25",
"Genero":"M",
"IdArea":1
},
{
"IdEmpleado":2,
"Nombre":"Luis",
"Edad":"30",
"Genero":"M",
"IdArea":2
}
]
I need to get the data for each employee, in the example are 2 employees need all the fields of each object and then turn them into employees.
I already use the JSON and transfer to an NSDICTIONARY, but how I can do to have it structured so each field and being able to pass a Method to convert an object EMPLOYEE?
http://stig.github.com/json-framework/
You can use the JSONFramework, which you can find here.
https://github.com/stig/json-framework/
NSString *userid= [[NSUserDefaults standardUserDefaults]objectForKey:#"Userid"];
NSString *appurl =[NSString stringWithFormat:#"your link"];
appurl = [appurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:appurl]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSMutableDictionary *deletdict=[returnString JSONValue];
if([[deletdict objectForKey:#"success"] isEqualToString:#"False"])
{
NSLog(#"Unsuccess...");
}
else
{
NSLog(#"success...");
}
AND Post method is this
NSString *post =[NSString stringWithFormat:#"AgencyId=STM&UserId=1&Type=1&Date=%#&Time=%#&Coords=%#&Image=h32979`7~U#)01123737373773&SeverityLevel=2",strDateLocal,strDateTime,dict];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://174.94.153.48:7778/TransitApi/IncidentConfirm/"]]];
[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];
NSMutableArray *SubLiveArray=[str JSONValue];
download Json framework on this link:::
http://mobile.tutsplus.com/tutorials/iphone/iphone-json-twitter-api
NSString *appurl=[NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=23.041230,72.514346&radius=50000&types=%#&sensor=true&key=AIzaSyAQZ16VzshxGbYdiM8C2RhhwGl3QwVJTB4",_txt_search.text];
I am trying to send the data to server and get the response. Data is reaching server but I am not getting any response. The value of response data is nil bcd of which it's throwing an exception,
-JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=11 \"Unexpected end of string\" UserInfo=0x4e2dd70 {NSLocalizedDescription=Unexpected end of string}"
Can anyone pls help me....
My code:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.0.83:8082/WebServiceProject/AcessWebservice?operation=login"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSError *theError = NULL;
NSArray *keys = [NSArray arrayWithObjects:#"UserId", #"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:#"rajin.sasi", #"abhi1551", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString* jsonString = [jsonDictionary JSONRepresentation];
SBJSON *jsonParser = [SBJSON new];
[jsonParser objectWithString:jsonString];
NSLog(#"Val of json parse obj is %#",jsonString);
[request setHTTPMethod:#"POST"];
[request setValue:jsonString forHTTPHeaderField:#"json"];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
[request setHTTPBody:responseData];
NSMutableString* stringData= [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDictionaryResponse = [stringData JSONValue];
NSString *json_message=[jsonDictionaryResponse objectForKey:#"message"];
printf("Json string is %s **********",[json_message UTF8String]);
I'm not privy of the particulars of your webservice, but the code below might be the source of your problem (or at least one of them!)
[request setValue:jsonString forHTTPHeaderField:#"json"];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
[request setHTTPBody:responseData];
You are sending the request before setting the body, which I assume should include your jsonString contents. Plus you're assigning your jsonString to a header field, are you sure that is what you want? Here's a guess at what might work:
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:jsonString];
responseData = // rest of your code here....
I suggest you have a good look through that code as it is a mess at the moment! You have two NSURLConnection requests going there, one asynchronous and one synchronous, it's kind of hard to understand what/why you are doing all of this so check Apple's documentation for NSURLConnection and tidy up your code...
[EDIT]
Here's my suggestion for you:
NSError *theError = nil;
NSArray *keys = [NSArray arrayWithObjects:#"UserId", #"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:#"rajin.sasi", #"abhi1551", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *jsonString = [jsonDictionary JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.0.83:8082/WebServiceProject/AcessWebservice?operation=login"]];
[request setValue:jsonString forHTTPHeaderField:#"json"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDictionaryResponse = [string JSONValue];
[string release];
[theResponse release];
NSData* responseData = nil;
NSURL *url=[NSURL URLWithString:[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *bodydata=[NSString stringWithFormat:#"%#",jsonString];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:req];
[request setTimeoutInterval:15.0];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSError *dataError;
NSMutableDictionary * jsonDict = [[NSMutableDictionary alloc]init];
if (responseData != nil)
{
jsonDict = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&dataError];
NSLog(#"jsonDict:%#",jsonDict);
}
Try this :
[request setValue:jsonString forHTTPHeaderField:#"json"];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
[request setHTTPBody:responseData];