How to post AES256 NSData to server using MKNetworKit? - aes

The username has been encrypted via RNCryptor and I would like to send the encrypted username to server using the MKNetworkKit. The encrypted username is in NSData format. But the MKNetworkKit seems not supporting the formats for the post body except NSDictionary.
So I follow the suggestion of using setCustomPostDataEncodingHandler to post the encrypted username. But it crashed. Please help review if something wrong in my below codes.
NSMutableDictionary * postDataDict = [NSMutableDictionary dictionaryWithObject:username forKey:#"username"];
MKNetworkOperation *op = [self operationWithPath:#"URLtomyserver/login.php"
params:postDataDict
httpMethod:#"POST"];
[op setCustomPostDataEncodingHandler:^NSString *(NSDictionary *postDataDict) {
NSData * username= [postDataDict objectForKey:#"username"];
NSString * postString = [[NSString alloc] initWithData:username encoding:NSUTF8StringEncoding];
return postString
} forType:#"application/json"];

Try this:
MKNetworkOperation *op = [self operationWithPath:INIT_URL params:body httpMethod:#"POST" ssl:YES];
[op setPostDataEncoding:MKNKPostDataEncodingTypeJSON];//This is important
[op addCompletionHandler:^(MKNetworkOperation *completedOperation)

Related

AFNetworking, upload simple NSData with POST

I created an NSDictionary containing arrays and strings and other client info, using setObject forKey. Everything looks great when I NSLog the data, format is exactly the way its supposed be. I've also converted my NSDictionary to NSData:
NSData *userData = [NSJSONSerialization dataWithJSONObject:userDict options:NSJSONWritingPrettyPrinted error:&error];
What I need to know is how to upload it to the server using POST. I've found the following code snippet to upload a photo. My question is can I simply use my NSDictionary as a parameter (params in request), it's kinda big. If not, how do I send my NSData object userData? I really love AFNetworking and have been using it exclusively for all my download needs. This is my first time uploading an object.
Thanks
NSData *imageData = UIImagePNGRepresentation(pageImage);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://www.SERVER.com"]];
//You can add POST parameteres here
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
author, #"author",
title, #"title",
nil];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"/PATH/TO/WEBSERVICE.php" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
//This is the image
[formData appendPartWithFileData: imageData name:#"cover_image" fileName:#"temp.png" mimeType:#"image/png"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//Setup Upload block to return progress of file upload
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
NSLog(#"Upload Percentage: %f %%", progress*100);
}];
//Setup Completeion block to return successful or failure
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
//Code to run after webservice returns success response code
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", [operation error]);
//Code to Run if Failed
}];
[operation start];
I am not sure I fully understand you question, but I will give it a try anyway.
My question is can I simply use my NSDictionary as a parameter (params in request), it's kinda big.
I think so. Just give it a try... in the end, those array will be converted in data sent to the server, so if the server is able to handle it, there should be no problem.
If not, how do I send my NSData object userData?
The data you send should be provided where the code you posted specifies imageData. Keep in mind that if what you are uploading is not meant to be a file (you mention NSData), then you might need to use appendPartWithFormData:name. This, again, depends on your server side.
Hope this clarifies things a bit.

How to handle Spanish character in my App?

In my app i have a service which supports spanish and return the result in spanish.
Now i am trying to pass some search term to this service to get the result back but its failing because while sending compiler converts the word to some funny word with unidentified characters.
I am doing this:
name here is coming in spanish but when i am adding this in the config dictionary it gets converted again to some funny thing.
-(void)perfromLocationSearchWithName:(NSString *)name{
NSData * nameCode = [[NSData alloc]init];
nameCode = [name dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString * namePass = [[NSString alloc]initWithData:nameCode encoding:NSUTF8StringEncoding];
NSLog(#"Name:%#",namePass);
NSMutableDictionary *config = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
NSString * strAction = [NSString stringWithFormat:#"vendorSearchByName"];
if (namePass !=nil){
[config setObject:namePass forKey:#"vendorName"];
//[config setObject:#"001" forKey:#"MakeCode"];
[config setObject:#"5" forKey:#"maxCount"];
[config setObject:strAction forKey:#"action"];
}
NSLog(#"Dict%#",[config description]);
comm = [[CommManager alloc] init];
[comm searchDealerLocationWithOptions:config withDelegate:self];
[namePass release];
}
Please help
Thanks,
Try using NSISOLatin1StringEncoding. Helped us in our app.

Error code -1011 when I use AFNetWorking

I am doing a service in our customer company. And I try to get some information from their server by AFNetWorking (Our customer encourage to use AFNetWorking)
I did some sample using AFNetWorking, and it's work.
But when I use one of our customer URLs to get JSON data, it failed and this is error description:
Error Domain=com.alamofire.networking.error Code=-1011
"Expected status code <NSIndexSet: 0x7e274f0>[number of indexes: 100 (in 1 ranges),
indexes: (200-299)], got 403" UserInfo=0x7b64040 {NSErrorFailingURLKey=<url_hidden_for_stackoverflow>,
NSLocalizedDescription=Expected status code <NSIndexSet: 0x7e274f0>[number of indexes: 100 (in 1 ranges), indexes: (200-299)], got 403}
I try to find out some solution, but I can't fix yet. There's my code:
NSURL *url = [NSURL URLWithString:#"http://example.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
//[httpClient setDefaultHeader:#"Accept" value:#"text/json"];
//NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:CONST_KEY_REGISTER_UNIQUE_KEY, CONST_API_KEY_TEXT,nil];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:#"path/to/page.json" parameters:nil];
[httpClient release];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSString *status = [JSON valueForKey:#"status"];
if ([status isEqualToString:#"OK"]) {
NSString *uniqueId = [JSON valueForKey:#"uniqueId"];
[UserSettings setWithKey:CONST_PROGRAM_UNIQUE_KEY value:uniqueId];
}
//NSString *message = [json valueForKey:#"message"];
//NSString *error = [json valueForKey:#"error"];
[[LoadingView instance] performSelectorOnMainThread:#selector(removeLoadingView) withObject:nil waitUntilDone:YES];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSString *errorString = [error description];
[[LoadingView instance] performSelectorOnMainThread:#selector(removeLoadingView) withObject:nil waitUntilDone:YES];
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
Thanks for reading, and any help or reply will be greatly appreciated.
EDIT: As DarkDust said: server deny my access. But I can get data from server by basic connection:
Here is code to get:
NSURL *url = [NSURL URLWithString:#"http://example.com/path/to/page.json"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:CONST_CONNECTION_TIMEOUT];
rssConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[self performSelectorOnMainThread:#selector(downloadStarted) withObject:nil waitUntilDone:NO];
if (rssConnection != nil) {
do {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
} while (!done);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// I can get text here, but it is not JSON format
NSString *content = [NSString stringWithUTF8String:[data bytes]];
}
I wonder why rssConnection can get JSON text and AFHTTPClient can not ?
As reference because of high search result via google...
For others that are looking for the possible error codes retrieved via AFNetworking, consult the apple documentation for URL Loading System Error Codes as these are the same.
NSURLErrorBadServerResponse = -1011
Returned when the URL Loading system receives bad data from the server.
This is equivalent to the “500 Server Error” message sent by HTTP servers.
The server is responding with the HTTP error code 403 which means Forbidden. It denies you access. You need to find out why, for example by reading the server logs (if you can) or asking the server administrator to help you. It might be access restrictions on the server that need to be lifted/modified.
Edit: A HTTP POST is an operation that wants to save something on the server. While the normal GET seems to work just fine according to your edited question, saving is prohibited right now. First thing to do is still examine the server configuration. Additionally, if your URL points to a script (JSP, ASP, whatever) which is the only thing that would make sense in your case you need to examine that to determine why it denies you access (if the server configuration doesn't already deny it, it must be the script).

Twitter API Rate Limit - Overcoming on an unauthenticated JSON Get with Objective C?

I see the rate limit is 150/hr per IP. This'd be fine, but my application is on a mobile phone network (with shared IP addresses).
I'd like to query twitter trends, e.g. GET /trends/1/json.
This doesn't require authorization, however what if the user first authorized with my application using OAuth, then hit the JSON API?
The request is built as follows:
- (void) queryTrends:(NSString *) WOEID {
NSString *urlString = [NSString stringWithFormat:#"http://api.twitter.com/1/trends/%#.json", WOEID];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
if (theConnection) {
// Create the NSMutableData to hold the received data.
theData = [[NSMutableData data] retain];
} else {
NSLog(#"Connection failed in Query Trends");
}
//NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
}
I have no idea how I'd build this request as an authenticated one however, and haven't seen any examples to this effect online.
I've read through the twitter OAuth documentation, but I'm still puzzled as to how it should work.
I've experimented with OAuth using Ben Gottlieb's prebuild library, and calling this in my first viewDidLoad:
OAuthViewController *oAuthVC = [[OAuthViewController alloc]
initWithNibName:#"OAuthTwitterDemoViewController" bundle:[NSBundle mainBundle]];
// [self setViewController:aViewController];
[[self navigationController] pushViewController:oAuthVC animated:YES];
This should store all the keys required in the app's preferences, I just need to know how to build the GET request after authorizing!
Maybe this just isn't possible? Maybe I'll have to proxy the requests through a server side application?
Any insight would be appreciated!
Authorizing through OAuth will provide you an authorization token, which you need to pass to each request you make later on.
Refer to Twitter docs, read about how authorization works.
Okay, after a lot of searching I've managed to figure how to construct a request to the JSON API programmatically in Xcode.
Firstly, you need to use the OAuth demo code to authenticate and authorize your application.
Then, you'll be retrieving the key by doing: [prefs stringForKey:#"authData"] - if this doesn't exist, you haven't been OAuth'd properly.
I had to reverse engineer this by looking through the code of the OAuth library, and while it's easy to use the library for stuff like sending a status update, it doesn't allow you to retrieve trends...:
#import "OAMutableURLRequest.h"
#import "MGTwitterHTTPURLConnection.h"
NSMutableString *dataString;
// Using OAuth:
OAConsumer *consumer = [[OAConsumer alloc] initWithKey:#"YOURCONSUMERKEY"
secret:#"YOURCONSUMERSECRET"];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *authData = [prefs stringForKey:#"authData"];
// [_engine
OAMutableURLRequest *theRequest = [[[OAMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://stream.twitter.com/1/statuses/filter.json"]
consumer:consumer
token: (authData) ? [[OAToken alloc] initWithHTTPResponseBody:authData] : nil
realm: nil
signatureProvider:nil] autorelease];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [httpBody dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest setHTTPShouldHandleCookies:NO];
// Set headers for client information, for tracking purposes at Twitter.
[theRequest setValue:#"Trendy" forHTTPHeaderField:#"X-Twitter-Client"];
[theRequest setValue:#"1.0" forHTTPHeaderField:#"X-Twitter-Client-Version"];
[theRequest setValue:#"http://www.inisdesign.com" forHTTPHeaderField:#"X-Twitter-Client-URL"];
// Set the request body if this is a POST request.
[theRequest prepare];
// Create a connection using this request, with the default timeout and caching policy,
// and appropriate Twitter request and response types for parsing and error reporting.
MGTwitterHTTPURLConnection *connection;
connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:theRequest
delegate:self
requestType:MGTwitterFollowedTimelineRequest // Wrong type
responseType:MGTwitterStatuses]; // as above - doesnt seem to matter
if (!connection) {
return;
} else {
// [_connections setObject:connection forKey:[connection identifier]];
// [connection release];
dataString = [[NSMutableData data] retain];
[connection start];
}
}
The rest is implemented as a standard URL connection with didReceiveData methods etc..
I haven't verified this is alleviating my rate limiting problems, but hey.. It's a start if anybody has similar problems.

Parsing Data returned from Twitpic API

I just wanted to ask you if anyone can help me parsing the returned data from the Twitpic API?
I'm creating a HTTPFormRequest using the ASIHTTPRequest Wrapper for Cocoa. This all happens in an iPhone application:
NSURL *url = [NSURL URLWithString:#"http://twitpic.com/api/upload"];
NSString *username = t_user;
NSString *password = t_pass;
NSData *twitpicImage = UIImagePNGRepresentation(imageView.image);
// Now, set up the post data:
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:twitpicImage forKey:#"media"];
[request setPostValue:username forKey:#"username"];
[request setPostValue:password forKey:#"password"];
[request setData:twitpicImage forKey:#"media"];
// Initiate the WebService request
[request start];
if ([request error]) {
NSLog(#"%#", [request error]);
} else if ([request responseString]) {
NSLog(#"%#", [request responseString]);
}}
Now comes the hard part, I don't know how to parse the data that is in [request responseString]. I know I need to use NSXMLParser, but I dunno how to use it. All I need is to get the url of the image.
Thx in advance.
Feel free to have a look at my little XML parse classes here http://www.memention.com/blog/2009/10/31/The-XML-Runner.html
I have started to use them for parsing the response from image upload to yfrog.com
Basically I do like this...
In NameValueParser.m I changed the entry tag to rsp like this
entryName = [[NSString stringWithString:#"rsp"] retain];
then where the response has been received I parse it like this
NameValueParser *parser = [NameValueParser parser];
[parser addFieldName:#"statusid"];
[parser addFieldName:#"userid"];
[parser addFieldName:#"mediaid"];
[parser addFieldName:#"mediaurl"];
[parser addFieldName:#"err"];
[parser parseData:responseData]; // the response received by ASIHTTPRequest
NSArray *rspArray = [parser list];
NSLog(#"%#", rspArray); // Have a look at it here
Try it as written at the bottom of this tutorial click here using NSScanner. They are showing exactly what you need, retrieving only the mediaurl = URL of uploaded image.
NSScanner *scanner = [NSScanner scannerWithString:responseString]; ...
GSTwitPicEngine does XML and JSON parsing both: http://github.com/Gurpartap/GSTwitPicEngine
Though, why not use JSON format for the Twitpic API responses? It's easy to parse and deal with using yajl, TouchJSON, json-framework or other Cocoa JSON libraries