encrypting in Objective-C decrypting nodejs - objective-c

I'm encrypting some text i want to send to a server and I have no problems encrypting it, and decrypting it in Objective-C but when I send it to the nodejs server the result by decrypting it never comes right the encrypted data comes always the same... I think the problem is how I use the crypto library, here's my Xcode code:
NSString * key =#"1234567890123456";
NSString * url = #"http://flystory.herokuapp.com/register";
NSString *post = #"hola mundo!!!!!!!!!!";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSLog(#"%#",[[NSString alloc] initWithData:postData encoding:NSASCIIStringEncoding]);
NSError *e;
CCCryptorStatus err;
postData = [postData dataEncryptedUsingAlgorithm:kCCAlgorithmAES128 key:key options:kCCOptionECBMode error:&err];
NSLog(#"%#",[[NSString alloc] initWithData:postData encoding:NSASCIIStringEncoding]);
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"post"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"body" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *r, NSData *d, NSError *e) {
if (e) NSLog(#"%#",e.description);
else [self handleRespondedData:d];
}];
postData = [postData decryptedDataUsingAlgorithm:kCCAlgorithmAES128 key:key options:kCCOptionECBMode error:&err];
NSLog(#"%#",[[NSString alloc] initWithData:postData encoding:NSASCIIStringEncoding]);
to encrypt I'm using this NSData extension contained in the NSData+CommonCrypto.h/m in https://github.com/Gurpartap/AESCrypt-ObjC
my Node.JS code goes as follows:
var express = require("express");
var app = express(express.bodyParser());
//...
app.post("*", function(request, response) {
var body = '';
request.setEncoding('hex');
request.on('data', function (data) {
body += data;
var crypto=require('crypto');
var decipher=crypto.createDecipher('aes-128-ecb', '1234567890123456');
decipher.setAutoPadding(auto_padding=false);
var enc = decipher.update(body, 'hex', 'utf8') + decipher.final('utf8');
console.log('encrypted: ' + body);
console.log('decrypted: ' + enc);
});
request.on('end', function () {
// use POST
route(handle, request.path, response, body);
});
});

Related

Posting JSON data to server

I am trying to post and JSON data to server.
My JSON is:
{
“username”:”sample”,
“password” : “password-1”
}
The way I am sending it to server is:
NSError *error;
NSString *data = [NSString stringWithFormat:#"{\"username\":\"%#\",\"password\":\"%#\"}",_textFieldUserName.text,_textFieldPasssword.text];
NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSData *jsonData = [NSJSONSerialization JSONObjectWithData:postData options:0 error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"My URL"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:requestHandler options:0 error:&error];
NSLog(#"resposne dicionary is %#",responseDictionary);
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
The JsonData that is created is a valid JSON accepted by the server.
But the app is crashing and the error is:
-[__NSCFDictionary length]: unrecognized selector sent to instance 0x1702654c0
what is wrong that i am doing here?
I always use this method in my apps to perform API calls. This is the post method. It is asynchronous so you can specify a callback to be called when the server answer.
-(void)placePostRequestWithURL:(NSString *)action withData:(NSDictionary *)dataToSend withHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *error))ourBlock {
NSString *urlString = [NSString stringWithFormat:#"%#", action];
NSLog(#"%#", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataToSend options:0 error:&error];
NSString *jsonString;
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *requestData = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
}
}
You can easily call it:
- (void) login:(NSDictionary *)data
calledBy:(id)calledBy
withSuccess:(SEL)successCallback
andFailure:(SEL)failureCallback{
[self placePostRequestWithURL:#"yourActionUrl"
withData:data
withHandler:^(NSURLResponse *response, NSData *rawData, NSError *error) {
NSString *string = [[NSString alloc] initWithData:rawData
encoding:NSUTF8StringEncoding];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
NSLog(#"%ld", (long)code);
if (!(code >= 200 && code < 300)) {
NSLog(#"ERROR (%ld): %#", (long)code, string);
[calledBy performSelector:failureCallback withObject:string];
} else {
NSLog(#"OK");
NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:
string, #"id",
nil];
[calledBy performSelector:successCallback withObject:result];
}
}];
}
And finally, you invocation:
NSDictionary *dataToSend = [NSDictionary dictionaryWithObjectsAndKeys:
_textFieldUserName.text, #"username",
_textFieldPasssword.text, #"password", nil];
[self login:dataToSend
calledBy:self
withSuccess:#selector(loginDidEnd:)
andFailure:#selector(loginFailure:)];
Don't forget to define your callbacks:
- (void)loginDidEnd:(id)result{
NSLog(#"loginDidEnd:");
// Do your actions
}
- (void)loginFailure:(id)result{
NSLog(#"loginFailure:");
// Do your actions
}
First you create an NSString* that is supposed to contain JSON data. This doesn't work in general if the username and password contain any unusual characters. For example, I make sure that I have a quotation mark in my password to make sure that stupid software crashes.
You turn that string into an NSData* using ASCII encoding. So if my username contains any characters that are not in the ASCII character set, what you get is nonsense.
You then use the parser to turn this into a dictionary or array, but store the result into an NSData. Chances are that the parse fails and you get nil, otherwise you get an NSDictionary* or an NSArray*, but most definitely not an NSData*.
Here's how you do it properly: You create a dictionary, and then turn it into NSData.
NSDictionary* dict = #{ #"username": _textFieldUserName.text,
#"password": _textFieldPasssword.text };
NSError* error;
NSData* data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
That's it.
try this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:#"My URL"];
if (!request) NSLog(#"Error creating the URL Request");
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"text/json" forHTTPHeaderField:#"Content-Type"];
NSLog(#"will create connection");
// Send a synchronous request
NSURLResponse * response = nil;
NSError * NSURLRequestError = nil;
NSData * responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&NSURLRequestError];

HTTP Post Request with Body Contents fails

i'm trying to send an HTTP post request from my objective-c application to my server. i tried many different things, but i can't get the request to work with the content on request body. With the parameters on the url it work just fine, but i need to send a string with reserved characters.
This is my class responsible for the request:
#import "CLPUtilRequest.h"
static NSString *baseURL = #"http://localhost:8080/cl-mobile";
#implementation CLPUtilRequest
//Parameteres on the URL (working!!)
+ (NSData *) makeHttpRequest:(NSString *)url {
//Set info for webservice
NSString *urlString = baseURL;
urlString = [urlString stringByAppendingString:url];
NSURL *resquestUrl = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:resquestUrl];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/http" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//Call the webservice
NSError *errorReturned = nil;
NSHTTPURLResponse *theResponse =[[NSHTTPURLResponse alloc]init];
return [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
}
//Parameteres on the bodt (not working!!)
+ (NSData *) makeHttpRequestContentOnBody:(NSString *)url withContent:(NSString *)content {
NSData *postData = [content dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *errorReturned = nil;
NSHTTPURLResponse *theResponse =[[NSHTTPURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
return data;
}
#end
And this is where i call the request.
NSString *contentString = #"chaveUsuarioEmpresa=";
contentString = [contentString stringByAppendingString:appDelegate.clinica.chave];
contentString = [contentString stringByAppendingString:#"&chaveAgendamento="];
contentString = [contentString stringByAppendingString:appDelegate.agendamento.chave];
contentString = [contentString stringByAppendingString:#"&anamnese="];
contentString = [contentString stringByAppendingString:self.texto.text];
NSData *dataResponse = [CLPUtilRequest makeHttpRequestContentOnBody:#"/agendamento/anamnese/save" withContent:contentString];
After calling the request, my errorReturned gives me the following (debugging): NSURLError * domain: #"NSURLErrorDomain" - code: -1002
I tried to do as described in this link (but didn`t make it): Sending an HTTP POST request on iOS
Thanks in advance!
according to Apple's Error Codes -1002 is the code for an unsupported url. and actually you are sending it to /agendamento/anamnese/save, as you don't prepend baseURL as you do in the other call
+ (NSData *) makeHttpRequest:(NSString *)url {
//Set info for webservice
NSString *urlString = baseURL;
urlString = [urlString stringByAppendingString:url];
NSURL *resquestUrl = [NSURL URLWithString:urlString];
while in makeHttpRequestContentOnBody:withContent: you use the unchanged passed in url string /agendamento/anamnese/save
Try
+ (NSData *) makeHttpRequestContentOnBody:(NSString *)url withContent:(NSString *)content
{
NSData *postData = [content dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *urlString = baseURL;
urlString = [urlString stringByAppendingString:url];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *errorReturned = nil;
NSHTTPURLResponse *theResponse =[[NSHTTPURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
return data;
}

How can I deal with a file being split into several parts, when I send it to a server?

I am trying to write code in Objective C which should send a JPEG file to a server. The problem is that the file is split into several parts, and only the first part is getting there. Is there a way of dealing with this?
Here is some of the code:
int j;
for (j = 0; j < 5; j++) {
// Read in data from appropriate signature file
NSMutableString *imagePath = [folder_path_2 mutableCopy];
[imagePath appendString:fn[j]];
[imagePath appendString:#".jpeg"];
NSLog(imagePath);
NSData *imageData = nil;
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
if (fileExists) {
imageData = [[NSData alloc] initWithContentsOfFile:imagePath];
} else {
NSLog(#"JPEG image file does not exist.");
}
request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlStr]];
[request setHTTPMethod:#"POST"];
[request setValue:#"image/jpeg" forHTTPHeaderField:#"Accept"];
[request setValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
int len = (int)[imageData length];
length_str = [NSString stringWithFormat: #"%d", len];
[request setValue:length_str forHTTPHeaderField:#"Content-Length"];
postBody = [NSMutableData data];
[postBody appendData:[NSData dataWithData:imageData]];
[request setHTTPBody:postBody];
// Make connection to the Internet
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil
error:nil];
NSString *returnString = (NSString*)[[NSString alloc] initWithData:returnData
encoding:NSUTF8StringEncoding];
NSLog(returnString);
}
How big is the jpeg file that you're trying to send?

JSON POST Request on the iPhone (Using HTTP) Problems

Im having problems with my request to a asp .net mvc web service. I read in a thread a while ago that its possible to find out what the server wants the the request's content-type to be etc. I get no error when compiling but when I do the actual request nothing happens and in the log of the server it only says (null) (null). There is no problem doing the GET request and fethcing all objects that are in the list. Can anyone please help me with this irritating bug? here is the code:
//----------------GET request to webservice works fine----------------------------------------
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url];
[request setHTTPMethod: #"GET"];
NSData *response = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
NSString *stringResponse = [[NSString alloc] initWithData: response encoding: NSUTF8StringEncoding];
//NSLog(#"stringResponse is %#", stringResponse);
//--------------------------------------------------------------------------------------------
NSString *twitterTrendsUrl=#"http://search.twitter.com/trends.json";
NSString *output=
[NSString stringWithContentsOfURL:[NSURL URLWithString:twitterTrendsUrl]];
id theObject= [output JSONValue];
NSLog(#"TWITTER: %#",theObject);
*/
//--------------------------------------------------------------------------------------------
NSURL *url = [NSURL URLWithString:#"http://errorreport.abou.se/Errors/1.0"];
//NSString *jsonRequest = #"{\"Description\":\"Gurras Description\",\"Category\":\"Klotter\"}";
//NSString *jsonRequest = #"{\"Description\":\"Gurras Description\",\"Category\":\"Klotter\",\"Address\":\"smedjegatan\",\"StreetNumber\":\"34\",\"Feedback\":\"True\",\"FeedbackWay\":\"Telefon\"}";
NSMutableDictionary* jsonObject = [NSMutableDictionary dictionary];
//NSMutableDictionary* metadata = [NSMutableDictionary dictionary];
//[metadata setObject:#"NewLoc" forKey:#"Uri"];
//[metadata setObject:#"Location.NewLoc" forKey:#"Type"];
//[jsonObject setObject:metadata forKey:#"__metadata"];
[jsonObject setObject:#"Gurras" forKey:#"Description"];
[jsonObject setObject:#"Klotter" forKey:#"Category"];
[jsonObject setObject:#"smedjegatan" forKey:#"Address"];
[jsonObject setObject:#"34" forKey:#"StreetNumber"];
[jsonObject setObject:#"True" forKey:#"Feedback"];
[jsonObject setObject:#"Telefon" forKey:#"FeedbackWay"];
// ... complete the other values
//
NSString* jsonRequest = [jsonObject JSONRepresentation];
// jsonString now contains your example strings.
NSLog(#"Request: %#", jsonRequest);
//NSURL *url = [NSURL URLWithString:#"https://mydomain.com/Method/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
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:#"json" forHTTPHeaderField:#"Data-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
//[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"returnData: %#", returnString);
I can also add an example of how to talk to the service with javascript:
<script type="text/javascript">
var obj = { "Description": "det kanske funkar" };
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Errors/1.0",
dataType: "json",
contentType: "application/json",
processData: true,
data: '{"Description": "STeffeent asdasd", "Category": "Miljö", "Address": "Bogatan","StreetNumber": "14", "Feedback": "true", "FeedbackWay": "Brev"}',
success: function (data) {
$("#result").text(data.Description);
}
});
});

Simple http post example in Objective-C?

I have a php webpage that requires a login (userid & password). I have the user enter the information into the app just fine.. but I need an example on how to do a POST request to a website. The apple example on the support site is rather complicated showing a picture upload.. mine should be simpler.. I just want to post 2 lines of text..
Anyone have any good examples?
Alex
This is what I recently used, and it worked fine for me:
NSString *post = #"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.nowhere.com/sendFormHere.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
Originally taken from http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html, but that blog does not seem to exist anymore.
From Apple's Official Website :
// In body data for the 'application/x-www-form-urlencoded' content type,
// form fields are separated by an ampersand. Note the absence of a
// leading ampersand.
NSString *bodyData = #"name=Jane+Doe&address=123+Main+St";
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://www.apple.com"]];
// Set the request's content type to application/x-www-form-urlencoded
[postRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// Designate the request a POST request and specify its body data
[postRequest setHTTPMethod:#"POST"];
[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
// Initialize the NSURLConnection and proceed as described in
// Retrieving the Contents of a URL
From : code with chris
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = #"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
ASIHTTPRequest makes network communication really easy
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:#"Ben" forKey:#"names"];
[request addPostValue:#"George" forKey:#"names"];
[request addFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photos"];
[request addData:imageData withFileName:#"george.jpg" andContentType:#"image/jpeg" forKey:#"photos"];
You can do using two options:
Using NSURLConnection:
NSURL* URL = [NSURL URLWithString:#"http://www.example.com/path"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
// Form URL-Encoded Body
NSDictionary* bodyParameters = #{
#"username": #"reallyrambody",
#"password": #"123456"
};
request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];
// Connection
NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil];
[connection start];
/*
* Utils: Add this section before your class implementation
*/
/**
This creates a new query parameters string from the given NSDictionary. For
example, if the input is #{#"day":#"Tuesday", #"month":#"January"}, the output
string will be #"day=Tuesday&month=January".
#param queryParameters The input dictionary.
#return The created parameters string.
*/
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
NSMutableArray* parts = [NSMutableArray array];
[queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
NSString *part = [NSString stringWithFormat: #"%#=%#",
[key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
[value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
];
[parts addObject:part];
}];
return [parts componentsJoinedByString: #"&"];
}
/**
Creates a new URL by adding the given query parameters.
#param URL The input URL.
#param queryParameters The query parameter dictionary to add.
#return A new NSURL.
*/
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
NSString* URLString = [NSString stringWithFormat:#"%#?%#",
[URL absoluteString],
NSStringFromQueryParameters(queryParameters)
];
return [NSURL URLWithString:URLString];
}
Using NSURLSession
- (void)sendRequest:(id)sender
{
/* Configure session, choose between:
* defaultSessionConfiguration
* ephemeralSessionConfiguration
* backgroundSessionConfigurationWithIdentifier:
And set session-wide properties, such as: HTTPAdditionalHeaders,
HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
*/
NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
/* Create session, and optionally set a NSURLSessionDelegate. */
NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
/* Create the Request:
Token Duplicate (POST http://www.example.com/path)
*/
NSURL* URL = [NSURL URLWithString:#"http://www.example.com/path"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
// Form URL-Encoded Body
NSDictionary* bodyParameters = #{
#"username": #"reallyram",
#"password": #"123456"
};
request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];
/* Start a new Task */
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil) {
// Success
NSLog(#"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);
}
else {
// Failure
NSLog(#"URL Session Task Failed: %#", [error localizedDescription]);
}
}];
[task resume];
}
/*
* Utils: Add this section before your class implementation
*/
/**
This creates a new query parameters string from the given NSDictionary. For
example, if the input is #{#"day":#"Tuesday", #"month":#"January"}, the output
string will be #"day=Tuesday&month=January".
#param queryParameters The input dictionary.
#return The created parameters string.
*/
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
NSMutableArray* parts = [NSMutableArray array];
[queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
NSString *part = [NSString stringWithFormat: #"%#=%#",
[key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
[value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
];
[parts addObject:part];
}];
return [parts componentsJoinedByString: #"&"];
}
/**
Creates a new URL by adding the given query parameters.
#param URL The input URL.
#param queryParameters The query parameter dictionary to add.
#return A new NSURL.
*/
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
NSString* URLString = [NSString stringWithFormat:#"%#?%#",
[URL absoluteString],
NSStringFromQueryParameters(queryParameters)
];
return [NSURL URLWithString:URLString];
}
I am a beginner in iPhone apps and I still have an issue although I followed the above advices. It looks like POST variables are not received by my server - not sure if it comes from php or objective-c code ...
the objective-c part (coded following Chris' protocol methodo)
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://example.php"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [NSString stringWithFormat:#"user_name=%#&password=%#", self.userNameField.text , self.passwordTextField.text];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
//NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSLog(#"Response: %#",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
Below the php part :
if (isset($_POST['user_name'],$_POST['password']))
{
// Create connection
$con2=mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// retrieve POST vars
$username = $_POST['user_name'];
$password = $_POST['password'];
$sql = "INSERT INTO myTable (user_name, password) VALUES ('$username', '$password')";
$retval = mysqli_query( $sql, $con2 );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysqli_close($con2);
}
}
else
{
echo "No data input in php";
}
I have been stuck the last days on this one.
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:#"name" forKey:#"email"];
[contentDictionary setValue:#"name" forKey:#"username"];
[contentDictionary setValue:#"name" forKey:#"password"];
[contentDictionary setValue:#"name" forKey:#"firstName"];
[contentDictionary setValue:#"name" forKey:#"lastName"];
NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonStr);
NSString *urlString = [NSString stringWithFormat:#"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:#"moinsam" password:#"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];
Thanks a lot it worked , please note I did a typo in php as it should be mysqli_query( $con2, $sql )
Here i'm adding sample code for http post print response and parsing as JSON if possible, it will handle everything async so your GUI will be refreshing just fine and will not freeze at all - which is important to notice.
//POST DATA
NSString *theBody = [NSString stringWithFormat:#"parameter=%#",YOUR_VAR_HERE];
NSData *bodyData = [theBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//URL CONFIG
NSString *serverURL = #"https://your-website-here.com";
NSString *downloadUrl = [NSString stringWithFormat:#"%#/your-friendly-url-here/json",serverURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: downloadUrl]];
//POST DATA SETUP
[request setHTTPMethod:#"POST"];
[request setHTTPBody:bodyData];
//DEBUG MESSAGE
NSLog(#"Trying to call ws %#",downloadUrl);
//EXEC CALL
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Download Error:%#",error.description);
}
if (data) {
//
// THIS CODE IS FOR PRINTING THE RESPONSE
//
NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(#"Response:%#",returnString);
//PARSE JSON RESPONSE
NSDictionary *json_response = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
if ( json_response ) {
if ( [json_response isKindOfClass:[NSDictionary class]] ) {
// do dictionary things
for ( NSString *key in [json_response allKeys] ) {
NSLog(#"%#: %#", key, json_response[key]);
}
}
else if ( [json_response isKindOfClass:[NSArray class]] ) {
NSLog(#"%#",json_response);
}
}
else {
NSLog(#"Error serializing JSON: %#", error);
NSLog(#"RAW RESPONSE: %#",data);
NSString *returnString2 = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(#"Response:%#",returnString2);
}
}
}];
Hope this helps!