I need to send request like this:
"http://api.site.com/login?q={"meta":{"api_key":"cb2f734a14ee3527b3"},"request":{"id":"username#host.name","password":"passw0rd"}}`
...the response to which should look like {"id":399205,"token":"d43f8b2fe37aa19ac7057701"} To do so, I have tried the following code:
self.responseData = [NSMutableData data];
NSDictionary *apiKeyDict = [NSDictionary dictionaryWithObject:#"cb2f734a14ee3527b3" forKey:#"api_key"];
NSDictionary *idPasswordDict = [NSDictionary dictionaryWithObjectsAndKeys:#"tc-d#gmail.com",#"id", #"abc",#"password", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:apiKeyDict, #"meta", idPasswordDict, #"request", nil];
NSURL *url = [NSURL URLWithString:#"http://api.site.com/login?="];
NSError *error = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
[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];
if (connection) {
self.recievedData = [NSMutableData data];
}
Later on, I get in the following:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.recievedData appendData:data];
NSLog(#"%#",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
The response data comes back as "<h1>CHttpException</h1><p>wrong sign</p>" As I understand, the way of adding json data to the current url is not appropriate in this case. Does anyone have advice on how I can fix this?
resolve my problem. Convert posted json to appended string to base url-string. that's how I did it:
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSMutableString *dictString = [[NSMutableString alloc]initWithData:requestData encoding:NSUTF8StringEncoding];
[dictString insertString:#"http://api.site.com/login?q=" atIndex:0];
//don't know why but dictString contains a lot of #"\n" and spaces to present it nice-formated.
[dictString replaceOccurrencesOfString:#"\n" withString:#"" options:nil range:NSMakeRange(0, dictString.length)];
[dictString replaceOccurrencesOfString:#" " withString:#"" options:nil range:NSMakeRange(0, dictString.length)];
NSURL *url = [NSURL URLWithString:[dictString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
if it helps someone will appreciate tick near this issue=)
You can do it right using AFNetworking library - it's easy to implement and to work with. Whole code you need in this case is quite simple and it was always working well for me.
NSDictionary *apiKeyDict = [NSDictionary dictionaryWithObject:#"cb2f734a14ee3527b3" forKey:#"api_key"];
NSDictionary *idPasswordDict = [NSDictionary dictionaryWithObjectsAndKeys:#"tc-d#gmail.com",#"id", #"abc",#"password", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:apiKeyDict, #"meta", idPasswordDict, #"request", nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *urlString = #"http://api.site.com/login";
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:jsonString, #"q", nil];
NSURL *url = [NSURL URLWithString:urlString];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:nil parameters:parameters];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//OK
NSLog(#"%#", JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
//Response failed
}];
[operation start];
Related
I am trying to upload a UIImage to .Net server by converting the image into base 64 and NSData. But I am getting the response null. Here is my code.
NSString *base64Encoded = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
NSString *post= [NSString stringWithFormat:#"myServerSideUrl?Image=%#",base64Encoded];
NSLog(#"PostData: %#",post);
NSString* webStringURL = [post stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:webStringURL];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[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" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSData *responseData = [[NSData alloc]initWithData:urlData];
if ([response statusCode] >=200 )
{
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData: responseData options:0 error:nil];
NSLog(#"%#",jsonData);
}
After some time, I just checked in postman showing like url too long HttpResponseCode:414. Also I tried to send the image in NSData format using AFNetwork, getting the same response. And I just googled about this, saying like send the base 64 string in body. When I tried to send image in body, server side can't get the image. They are creating the API like GET method but the actual method is POST. Is there any other solution about this. Any suggestions.
You are setting NSData to your request body without defining any key-value pair.
Try this code using AFNetworking...
- (void) uploadFileRequestWithHttpHeaders:(NSMutableDictionary*) headers
withServiceName:(NSString*) serviceName
withParameters:(NSMutableDictionary*) params
withFileData:(NSArray*) files
{
NSString *serviceUrl = [httpBaseURL stringByAppendingPathComponent:serviceName];
if (headers == nil)
{
NSDictionary *headers = [[NSDictionary alloc] initWithObjectsAndKeys:#"multipart/form-data",#"Content-Type",nil];
[self setHeaders:headers];
}
else
{
[headers setObject:#"multipart/form-data" forKey:#"Content-Type"];
[self setHeaders:headers];
}
[httpSessionManager POST:serviceUrl
parameters:params
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
for (NSData *fileData in files)
{
[formData appendPartWithFileData:fileData name:#"userProfileImg" fileName:#"profile_pic.jpg" mimeType:#"image/jpeg"];
}
}
success:^(NSURLSessionDataTask *task, id responseObject) {
if (success != nil)
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
if (failure != nil)
}];
}
- (void) setHeaders:(NSDictionary*) headers
{
if (headers != nil)
{
NSArray *allHeaders = [headers allKeys];
for (NSString *key in allHeaders)
{
[httpSessionManager.requestSerializer setValue:[headers objectForKey:key] forHTTPHeaderField:key];
}
}
}
- (void) addQueryStringWithParams:(NSDictionary*) params
{
[httpSessionManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
__block NSMutableString *query = [NSMutableString stringWithString:#""];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&err];
NSMutableString *jsonString = [[NSMutableString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
query = jsonString;
return query;
}];
}
And call this method like this..
NSArray *objects = [NSArray arrayWithObjects:#"multipart/form-data",#"1.0",#"ios",token, nil];
NSArray *Keys = [NSArray arrayWithObjects:#"content-type",#"version",#"os",#"token", nil];
NSMutableDictionary *headers = [[NSMutableDictionary alloc]initWithObjects:objects forKeys:Keys];
NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] init];
[paraDic setObject:self.userNameField.text forKey:#"name"];
NSData * userProfileImg = UIImageJPEGRepresentation(image, 0.8f);
imageDataArray = [NSArray arrayWithObjects:userProfileImg, nil];
[self uploadFileRequestWithHttpHeaders:headers withServiceName:#"updateProfile" withParameters:params withFileData:files];
You can try this code using NSURLSession-
- (void)postRequestForSubmitDataToServer {
//Put your action URL
NSURL *aUrl = [NSURL URLWithString:#"action_url.php?&attachment=att&submit=submit"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil) {
//change JSON type according to ur need.
NSArray *JSON = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"Data = %#",JSON);
} else {
NSLog(#"%#", error);
}
}];
[postDataTask resume];
}
My form data-
<form action="action_url.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="attachment" size="25" /><br>
<input type="submit" name="submit" value="Submit" /> </form>
I need to bind parameters in an object and pass the object as a POST request to receive a successful piece of information from an API.
{
customer = {
"auth_token" = "";
"device_id" = 3e708bf1a49cdd06;
"email_address" = "abc#xyz.in";
name = abc;
number = 1234567890;
"resend_token" = true;
};
}
This is the object that I need to send along with the post request. But when I convert it into a string and post it, the entire object becomes the key and the value becomes nil. It gets posted as {"{customer.....}=>nil}.
The object should be posted as
{"customer:
{"auth_token":"","device_id":"3e708bf1a49cdd06","email_address":"abc#xyz.in",
"name":"abc","number":"1234567890","resend_token":"true"}}
This my current attempt:
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
NSString *postString = [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setHTTPMethod:#"POST"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
A lot of the code used here was used without a proper understanding and directly taken from other StackOverflow answers, so please excuse any bad programming practice.
How can I do this? Any help is appreciated. Thank you.
you can try below code.Instead of converting data to string set it as HTTPBody like
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = temp;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setHTTPMethod:#"POST"];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Following is the sample code for sending a POST request to server.
-(void)doRequestPost:(NSString*)url andData:(NSDictionary*)data{
requestDic = [NSDictionary dictionaryWithDictionary:data];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:nil];
NSString *jsonString=[[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSStringEncodingConversionAllowLossy];
NSLog(#"Request Object:\n%#\n",data);
NSLog(#"Request String:\n%#\n",jsonString);
NSMutableURLRequest *theReq=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[theReq addValue: #"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theReq setHTTPMethod:#"POST"];
[theReq addValue:[NSString stringWithFormat:#"%lu",(unsigned long)[jsonString length]] forHTTPHeaderField:#"Content-Length"];
[theReq setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
connection = [NSURLConnection connectionWithRequest:theReq delegate:self];
}
May this help lot and resolve your problem.
NSString *post =[[NSString alloc] initWithFormat:#"id=%d&restaurant_name=%#", restaurnt_Id, _rest_NameTxt.text];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:EDIT_RESTAURANT_API];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[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" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
_responseData = [[NSMutableData alloc] init];
[NSURLConnection connectionWithRequest:request delegate:self];
pragma mark - connection methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_responseData setLength:0];
[_responseCityData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseData appendData:data];
[_responseCityData appendData:data];
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[COMMON showErrorAlert:#"Internet Connection Error!"];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
responseString = [responseString stringByReplacingOccurrencesOfString:#"\n" withString:#" "];
NSLog(#"%#", responseString);
}
Make your task in connectionDidFinishLoading method
I have tried using NSURLRequest to send NSString to server without using key-value pair but got the response as null value. Can anyone please provide information regarding this?
Thank you in advance...
code which I have tried:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:someUrl];
[request setHTTPMethod:#"POST"];
NSString *post = [NSString stringWithFormat:#"%#",someString];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[someUrl host]];
NSError *error=nil;
// generates an autoreleased NSURLConnection
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
NSURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *string = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:returnData //1
options:kNilOptions
error:&error];
NSLog(#" json %# ",json);
I want to reach from ios to a .net .asmx web service, and I reach with the following code:
NSString *urlString = #"http://www.****.com/Mobile.asmx/HelloWorld";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
//...do something with the returned value
}
It returns clean json {"hellom":"Hello World","hellom2":"HelloWorld2"} but I can't reach members and value one by one
How can I do that?
You can convert JSON data into an object by using the following code...
NSData *jsonData = ... the data you got from the server
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
object will then be a NSDictionary like this...
#{
hellom : #"Hello World",
hellom2: #"HelloWorld2"
}
You can then get to the keys and values like any other dictionary.
This is my code for sending a post request to a nodejs backend.
CLLocation* location = [locationManager location];
CLLocationCoordinate2D coord = [location coordinate];
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://50.63.172.74:8080/points"]];
//[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSDictionary* jsonDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:coord.latitude], #"lat", [NSNumber numberWithFloat:coord.longitude], #"lng", nil];//dictionaryWithObjectsAndKeys:coord.latitude, nil]
NSString *postString;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
postString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
Using express I'm getting the request.body back on the server but it looks like this:
{ '{\n "lat" : 0.0,\n "lng" : 0.0\n}': '' }
and I can't access it by just saying request.body.lat since it comes back as undefined.
I want the body to look like:
{ "lat":0.0, "lng":0.0}
Any idea on how to do that using express?
May this help you.
Please replace 0.0 with your actual coordiantes
NSArray *keys = [NSArray arrayWithObjects:#"lat", #"lng", nil];
NSArray *objects = [NSArray arrayWithObjects:#"0.0",#"0.0", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData ;
NSString *jsonString;
if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSString *requestString = [NSString stringWithFormat:
#"http://50.63.172.74:8080/points"];
NSURL *url = [NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: jsonData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
NSLog(#"Error %#",errorReturned.description);
}
else
{
NSError *jsonParsingError = nil;
NSMutableArray *arrDoctorInfo = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError];
NSLog(#"Dict %#",arrDoctorInfo);
}
The problem is that after you use NSJSONSerialization to obtain a NSData object containing your JSON data, you then create postString from that data. Eliminate that unnecessary step, and just do:
[request setHTTPBody:jsonData];
And you should get the expected JSON in your server-side code.