Request data
NSDictionary *tmp = #{#"name":#"Kousik",#"age":#"24",#"location":#"bangalore"};
NSString *postdata = [NSString stringWithFormat:#"request = %#",tmp];
//now postdata is
//request = {
"age" = "24";
"location" = "bangalore";
"name" = "Kousik";
}
but I want this NSDictionary should be inside a string so that in server I can eval it and get the dictionary back.
Here I want something like toString() is java or str() in pyhton.
This is my Http request:-
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:path]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSData *preparedPostData = [postdata dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postdata length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:preparedPostData ];
[NSURLConnection sendAsynchronousRequest:request
queue:backgroundQueue
completionHandler:^(NSURLResponse response,NSData data,NSError *error){
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
if(complect)
complect(result,error);
}
];
Update
My request is going to server properly but The problem is with data structure.
when I am trying to access the data with request key then it is giving error because the value for the request key is not supported in server as this value is having = sign in between. So what I want is that to make the requset data structure properly.want to send the NSDictionary itself as a string.
postdata should be something like this
request = "{
age : 24;
location : bangalore;
name : Kousik;
}"
I dont want to use application/json.
NSString *stringURL = [NSString stringWithFormat:#"name=%#&age=%#&location=%#",#"Kousik",#"24",#"bangalore"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",ServerURL,API_SaveContctListToAddressBook]]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[stringURL dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!data) {
data = [[NSData alloc] init];
}
NSDictionary *dic =[ NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&connectionError];
completionHandler(dic, NO);
}];
Use NSJSONSerialization to convert your dictionary to NSData and then attach it on HTTPBody
NSData *httpBody = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",ServerURL,APIPath]]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:httpBody];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//Handling code
}];
Related
I have tried many times, but i cant do a simple POST request to a remote API.. I need to post username and password to get a login authorization. Here are the code:
NSURL * url = [NSURL URLWithString:#"http://thapi.xyz/auth/login"];
NSString *postData = #"username=emailExample#gmail.com&password=123456";
NSData * dataBody = [postData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLenght = [NSString stringWithFormat:#"%d",[dataBody length]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-unlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLenght forHTTPHeaderField:#"Content-Lenght"];
[request setHTTPBody:dataBody];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(#" ERROR %#, RESPONSE %# AND DATA %#",connectionError,response,[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}];
I have made another version, witch uses NSDictionary and Json parsing (the API uses json)
NSDictionary * login = #{#"username":#"exampleMail#gmail",#"password":#"123456"};
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:login options:NSJSONWritingPrettyPrinted error:nil];
NSString *postLenght = [NSString stringWithFormat:#"%d",[jsonData length]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-unlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLenght forHTTPHeaderField:#"Content-Lenght"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(#" ERROR %#, RESPONSE %# AND DATA %#",connectionError,response,[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}];
And here is the result of both codes:
2016-06-18 05:24:20.329 Hoffmann iOS[10317:1088208]
ERROR (null), RESPONSE <NSHTTPURLResponse: 0x796bee60>
{ URL: http://thapi.xyz/auth/login } { status code: 400, headers {
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 70;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sat, 18 Jun 2016 04:24:18 GMT";
Etag = "W/\"46-22Kcj8zTKrWgQ7OCr429+w\"";
Server = "nginx/1.6.2";
Vary = "Accept-Encoding";
"X-Powered-By" = undefined;
"X-Response-Time" = "5.357ms";
} } AND DATA {"name":"ParameterError","message":"Request should contain: username"}
I really appreciate all answers, and sorry for my bad english...
Perhaps the misspelling of the header variable is the issue ("Content-Lenght" is misspelled):
[request setValue:postLenght forHTTPHeaderField:#"Content-Length"];
NSURLConnection is deprecated. use nsurlsession instead Try this code....
//replace the following code with your request params
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *clientSessionId = [prefs stringForKey:#"clientSession"];
NSString *bodyString = [NSString stringWithFormat:#"[\"%#\",{\"session_token\":\"%#\",\"request\":[\"GetUnitDetails\",{}]}]",clientSessionId,clientSessionId];
//Make mutable url request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[Settings getMobileUrl]]];
NSData *postData = [bodyString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
//Change the http method as per your own choice
[request setHTTPMethod:#"POST"];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *connectionError)
{
if ([data length] > 0 && connectionError == nil)
{
NSError *localError = nil;
self.parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&localError];
NSString* unitResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [unitResponse dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
}else {
NSLog(#"No response received");
}
}]resume];
You could try using a NSDictionary for the parameters. The following will send the parameters correctly to a JSON server.
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://thapi.xyz/auth/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *login = [[NSDictionary alloc] initWithObjectsAndKeys: #"username":#"exampleMail#gmail",#"password":#"123456",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:login options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
Hope this works Properly...:)
try also to correct "setValue:postLenght", since I guess that doesn't exist, and will probably set Content-Length to 0.
NSString *AuthToken = [[NSUserDefaults standardUserDefaults]
stringForKey:#"AuthToken"];
NSString* json =[NSString stringWithFormat:#"{'DeviceId':'%#','DeviceType':'iOS','UM_Identifier':'%#','AuthToken':'%#','Query':'all'}", deviceId, userEmail, AuthToken];
NSString *post =[[NSString alloc] initWithFormat:#"jinpAllCustDetails=%#",json];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://www.google.com"]];
NSData *postData = [post dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
In above code :
Auth token received from last webservice response is saved in NSUserdefaults,
then used for next webservice request.
So for Eg.
Send auth token : z71VxyfVlBxvNKJ01m64a4oKV9lWEv+fFhHxi+7zyRw=
But server would receives it as :z71VxyfVlBxvNKJ01m64a4oKV9lWEv fFhHxi 7zyRw=
ie All occurrences of "+" are replaced by " ". So server considers it as an invalid auth token and the webservices request returns a result accordingly.
Help me to fix this, thanks in advance
That isn't valid JSON as strings should be surrounded with ". Create an NSDictionary of the values and use NSJSONSerialization to create the JSON string, which you know will be valid:
NSDictionary *values = #[
#"DeviceId": deviceId,
#"DeviceType": #"iOS",
#"UM_Identifier": userEmail,
#"AuthToken": authToken,
#"Query": #"all"
];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:values
options:0
error:&error];
NSAssert(jsonData != nil, #"Failed to create JSON data");
NSString jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
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.
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];
I have the following code, which should simply load a URL with post data, and then grab the HTML response from the server:
// Send log in request to server
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#", text_field_menu_username.text, text_field_menu_password.text];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request;
[request setURL:[NSURL URLWithString:#"http://example.com/test.php"]]; // Example Only
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
// Handle response
NSString *response_string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data 1: %#", response);
NSLog(#"Data 2: %#", data);
NSLog(#"Data 3: %#", error);
NSLog(#"Data 4: %#", response_string);
}];
Here's the output from each of the NSLog's:
Data 1: (null)
Data 2: (null)
Data 3: (null)
Data 4:
Any idea what I am doing wrong?
You haven't initialized the request object before setting its parameters. It should be:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];