Using NSOutputStream to POST to url - cocoa

So all I want to do is send a POST request to a url. Now I tried using NSURLRequest/NSURLConnection, but was having problems with that and decided to move to a lower level, also because I want to send large files and thought dealing directly with streams might be better. But the output stream delegate never seems to be called, and I can't seem to find examples using NSOutputStream's initWithURL.
NSURL *url = [NSURL URLWithString:NSString stringWithFormat: #"http://url"];
self.outputStream = [[NSOutputStream alloc] initWithURL:url append:NO];
[outputStream retain];
[outputStream setDelegate:self];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream open];
It seems that the outputStream is null after the init, which I can't understand because my url is a valid url--I can ping it from the terminal and send data from other sources. Am I doing something wrong, or can anyone tell me how to write a POST request to a URL using streams? Thanks.

You cannot use NSOutputStream to send a POST request to a HTTP server.
The good method is to create a NSMutableURLRequest and provide that request with a HTTPBodyStream then create a NSURLConnection to send the request.
The HTTPBodyStream is an NSInputStream the request will read the body from. You may initialize it with a NSData object or with the contents of a file.
If you want to provide a custom content (for example, you want to upload a file as part of a multipart/form-data request), you may need to subclass NSInputStream. In such case, I suggest you to have a look at How to implement CoreFoundation toll-free bridged NSInputStream subclass, which explains how to address an issue that occurs when using custom input streams with NSURLConnection. Or you may use ASIHTTPRequest which provides multipart HTTP requests out of the box.

Yes, you can send the HTTP GET/POST request using NSOutputStream.
1.make & open your stream.
2.when the stream is ready to write, the NSStreamEventHasSpaceAvailable event will be send in method:
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
https://developer.apple.com/documentation/foundation/nsstreamdelegate/1410079-stream?language=objc
3.make a CFHTTPMessageRef & and write the data.
code like this:
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
switch (eventCode) {
case NSStreamEventOpenCompleted:{
//
}
break;
case NSStreamEventHasSpaceAvailable:{
[self sendHTTPMessage];
}
break;
default:{
//
}
break;
}
- (void)sendHTTPMessage{
//create a http GET message
CFStringRef requestMethod = (CFStringRef)CFAutorelease(CFSTR("GET"));
CFHTTPMessageRef httpRequest = (CFHTTPMessageRef)CFAutorelease(CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, (__bridge CFURLRef)yourURL,kCFHTTPVersion1_1));
//set HTTP header
CFHTTPMessageSetHeaderFieldValue(httpRequest, (__bridge CFStringRef)#"Host", (__bridge CFStringRef)#"yourhost.com");
CFHTTPMessageSetHeaderFieldValue(httpRequest, (__bridge CFStringRef)#"Connection", (__bridge CFStringRef)#"close");
//set HTTP Body
...
//let's send it
CFDataRef serializedRequest = CFHTTPMessageCopySerializedMessage(httpRequest);
NSData *requestData = (__bridge_transfer NSData *)serializedRequest;
[self.outStream write:requestData.bytes maxLength:requestData.length];
[self.outStream close];
}
Remember, the key point is converting CFHTTPMessageRef to bytes to write.

Related

How to convert NSData deviceToken to JSON-compatible string to remote API

I need to use the PushWoosh RemoteAPI to register my device.
What is the recommended way to send the deviceIDToken as JSON to the service?
The DeviceID is a NSDATA, but to send it to the remote API I need to convert it to a string.
Which encoding should I use?
NSString *tokenString = [[NSString alloc] initWithData:deviceToken encoding:NSASCIIStringEncoding];
Leads to strange data and is not accepted as a deviceToken.?
My app use this method below, I don't think it is a perfect way for it but it works
NSString *strToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]] ;
You can try this one for Remote API register, it might help :)
{
"request":{
"application":"APPLICATION_CODE",
"push_token":"DEVICE_PUSH_TOKEN",
"language":"en", // optional
"hwid": "hardware device id",
"timezone": 3600, // offset in seconds
"device_type":1
}
}

Parameters are always null when AFJSONRequestSerializer is used for a POST in AFNetworking

I'm writing a REST API by using SlimFramework in server side and AFNetworking in client side.
I'd like to add a value in Header for Authorization so that I'm using AFJSONRequestSerializer before the POST. Here is my code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:self.apikey forHTTPHeaderField:#"Authorization"];
[manager POST:url parameters:#{REST_PARAM_USERID: userId}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
But the failure callback is always called. I found that's because the parameters I passed to server are always null although they're not null when I debugged in my Xcode. When I comments out the requestSerializer then my server works well.I don't know what's the reason. Can anybody help? Thanks
When you use AFJSONRequestSerializer, your parameters will always be serialized as JSON in the body of the HTTP request. If your server is not expecting JSON, then you should either reconfigure your server, or not use AFJSONRequestSerializer.
If, for some reason, you want to send some parameters through normal URL encoding, and others through JSON, you'll need to manually append them to your URL like so:
NSString *urlWithParams = [NSString stringWithFormat:#"%#?%#=%#", url, REST_PARAM_USERID, userId"];
[manager POST:urlWithParams parameters:#{#"some other" : #"params"}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];

Restkit: migrating to 0.20

I am trying to migrate to RestKit 0.20-pre2.
Currently I managed to migrate my mapping (at least the compiler does not complain anymore), but I have problems in creating requests (previously I used the RKObjectLoader which does not exist anymore.
My previous code is the following:
- (RKObjectLoader*)objectLoaderWithResourcePath: (NSString*)resourcePath
method: (RKRequestMethod)httpMethod
parameters: (NSDictionary*)parameters
mappableClass: (Class)objectClass
{
RKObjectMapping *mapping = [self.objectManager.mappingProvider objectMappingForClass:objectClass];
NSString *path = resourcePath;
if (httpMethod == RKRequestMethodGET) {
path = [resourcePath stringByAppendingQueryParameters:parameters];
}
RKObjectLoader *request = [self.objectManager loaderWithResourcePath:path];
request.method = httpMethod;
request.delegate = self;
request.objectMapping = mapping;
if (httpMethod != RKRequestMethodGET) {
request.params = parameters;
}
return request;
}
I used the above method to create a generic request, and then send it either synchronously or asynchronously.
Now... I saw the new method getObjectsAtPath: parameters: success: failure:, but.. I need the same for the POST (and I don't have any object to post... it is simply the server which accept a POST request for the login..)
Any help?
Thank you
I had the same problem as you and i received a great answer here:
Trying to make a POST request with RestKit and map the response to Core Data
Basically,
This is what you need:
NSDictionary *dictionary = #{ #"firstParam": #(12345), #"secondParam": #"whatever"};
NSMutableURLRequest *request = [objectManager requestWithObject:nil method:RKRequestMethodPOST path:#"/whatever" parameters:parameters];
RKObjectRequestOperation *operation = [objectManager objectRequestOperationWithRequest:request ^(RKObjectRequestOperation *operation, RKMappingResult *result) {
NSLog(#"Loading mapping result: %#", result);
} failure:nil];
There is an example here in README section Managed Object Request that will help you:
https://github.com/RestKit/RestKit
You can use AFNetworking directly using the RK HTTPClient subclass, something like this:
[[RKObjectManager sharedManager].HTTPClient postPath:#"/auth" parameters:params success:^(AFHTTPRequestOperation *operation, id JSON)
{
// Success
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
// Error
}];
Since RestKit v0.20.x, RK now use AFNetworking under the hood instead of RKClient, so you can refer directly to the AFNetworking docs:
http://afnetworking.github.com/AFNetworking/Classes/AFHTTPClient.html#//api/name/postPath:parameters:success:failure:
Edit
In my project, for the auth, I simply created an NSObject named User, with a singleton, and managed the mapping myself. I (personally) didn't need to have my auth user in my core data stack. If you need to use the RK Core data mapping capabilities, take a look at RKObjectManager with the postObject:path:parameters:success:failure: method.

RestKit image upload parameters

I've made multiple attempts to enable POST image file transfer with RestKit but have only succeeded so far using curl. The working code is below, but it is synchronous and makes the UI unresponsive.
NSArray *arguments =
[NSArrayarrayWithObjects:assetScriptFullPath,
#"-F", [NSString stringWithFormat:#"asset[file]=#%#", fullPath],
#"-F", [NSString stringWithFormat:#"asset[user_id]=%d", user_id],
#"-F", [NSString stringWithFormat:#"asset[checksum]=%s", [(NSString *)md5hash UTF8String]],
nil];
NSTask *task = [NSTasklaunchedTaskWithLaunchPath:#"/usr/bin/curl"arguments:arguments];
The curl call is received at the server as below:
{
"asset"=>{
"file"=>#<ActionDispatch::Http::UploadedFile:0xcfcc630
#original_filename="IMG_6236.JPG",
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"asset[file]\"; filename=\"IMG_6272.JPG\"\r\nContent-Type: image/jpeg\r\n",
#tempfile=#<File:/tmp/RackMultipart20121117-21489-brm3b9>>,
"user_id"=>"522",
"checksum"=>"ab23bc492bac990d9022248315c743c1"
}
}
One attempt with RestKit is based on this post ( RestKit Image Upload ) but doesn't nest file within asset. My attempts to nest the params within 'asset' haven't worked or have crashed.
{
"user_id"=>"522",
"checksum"=>"ab23bc492bac990d9022248315c743c1",
"file"=>#<ActionDispatch::Http::UploadedFile:0x883eb9c
#original_filename="file",
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"file\"; filename=\"file\"\r\nContent-Type: image/jpeg\r\n",
#tempfile=#<File:/tmp/RackMultipart20121125-25702-ac8ck9>>
}
Using the method described in the RestKit advanced tutorial below I either can't get the hierarchy I need (file within asset) or I can't get the image data attached without crashing.
https://github.com/RestKit/RestKit/blob/master/Docs/MobileTuts%20Advanced%20RestKit/Advanced_RestKit_Tutorial.md
One way I tried to attach the image that causes crashes is described here:
Serialize nested image in RestKit (Rails Backend)
{
"asset"=>{
"user_id"=>"522",
"file"=>"#/Users/dev/IMG_6236.JPG",
"checksum"=>"ab23bc492bac990d9022248315c743c1"
}
}
Any recommendations? Thanks!
If I could change what the server expects I can get it to work with a flat parameter hierarchy. This isn't a solution though, I can't change the hierarchy. The code is below:
[params setFile:asset forParam:#"file"];
[params setData:[name dataUsingEncoding:NSUTF8StringEncoding] forParam:#"name"];
[params setData:[user_id dataUsingEncoding:NSUTF8StringEncoding] forParam:#"user_id"];
[client post:assetScriptPath params:params delegate:self];
This is what the server sees, but I need this all within an "asset" as above.
{
"file"=>#<ActionDispatch::Http::UploadedFile:0xcfcc630
#original_filename="IMG_6236.JPG",
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"file\"; filename=\"IMG_6272.JPG\"\r\nContent-Type: image/jpeg\r\n",
#tempfile=#<File:/tmp/RackMultipart20121117-21489-brm3b9>>,
"user_id"=>"522",
"checksum"=>"ab23bc492bac990d9022248315c743c1"
}
The way we do it is we encode the image into base64Encoding and decode it on the server side.
Something like this.
NSData *imageData = [NSData dataWithData:imageForUpload];
NSString *encodedString = [imageData base64Encoding];
After that it works just like a regular RestKit post.

Uploading a file with POST using AFNetworking

So I'm trying to upload an XML file to a server with POST using AFNetworking.
So using example code from their site I have this set up. When it runs, something is uploaded to the server (or at least it leaves my computer). I can monitor the upload, when the upload is finished, the server recognizes that it completed and goes to load the file, but it loads an old XML. So its connecting properly to the server, but I'm not sure why the file upload isn’t working correctly. Also I just want to send the file, the server doesn’t need any headers or parameters etc.
So I'm wondering if I’ve stored the data correctly? Or if I'm not sending it the server properly or what? Any suggestions would be helpful
NSData *iTunesXMLData = [NSData dataWithContentsOfFile:filePath];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
/* NSMutableURLRequest *request =[httpClientmultipartFormRequestWithMethod:#"POST"
path:#"/upload.php?id=5" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:iTunesXMLData name:#"iTunes Music Library" fileName:#"iTunes Music Library.xml" mimeType:#"application/xml"];
}];*/
//I tried this way also, both did the same thing
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"/upload.php?id=5" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFormData:iTunesXMLData name:#"iTunes Music Library"];
}];`
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];`
NSLog(#"Operation: %#", operation);
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation start];
Have you tried to catch the success/failure of the operation? Try this after setUploadProgressBlock:
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// Operation ended successfully
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Something happened!
NSLog(#"ERROR: %#, %#", operation, error);
// Here you can catch operation.responseString to see the response of your server
}];
This is an easy way to know what your server returned. If something uploads to your server, double check that you're getting the right file. AFAIK, your AFNetwork seems ok.

Resources