HTTP POST to Imageshack - iphone

I am currently uploading images to my server via HTTP POST. Everything works fine using the code below.
NSString *UDID = md5([UIDevice currentDevice].uniqueIdentifier);
NSString *filename = [NSString stringWithFormat:#"%#-%#", UDID, [NSDate date]];
NSString *urlString = #"http://taptation.com/stationary_data/index.php";
request= [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:imageData]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(returnString);
However, when I try to convert this to work with Image Shacks XML API, it doesn't return anything. The directions from ImageShack are below.
Send the following variables via POST to imageshack. us /index.php
fileupload; (the image)
xml = "yes"; (specifies the return of XML)
cookie; (registration code, optional)
Does anyone know where I should go from here?

You might want to consider using ASIHTTPRequest, as it will build a form data post body for you with a lot less hassle, and can stream the request body from disk, so you'll save memory when uploading large images.
A quick google found this, which seems to suggest you should be posting to /upload_api.php rather than /index.php.
Something like this would probably be a good start:
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithUrl:[NSURL URLWithString:#"http://www.imageshack.us/upload_api.php"]] autorelease];
[request setFile:#"/path/to/file" forKey:#"fileupload"];
[request setPostValue:#"yes" forKey:#"xml"];
[request setPostValue:#"blahblah" forKey:#"cookie"];
//It looks as though you probably need these too
[request setPostValue:#"me#somewhere.com" forKey:#"email"];
[request setPostValue:#"blah" forKey:#"key"];
[request start];
if ([request error]) {
NSLog(#"%#",[request error]);
} else {
    NSLog([request responseString]); // The xml that got sent back
}
Warning: untested!
I've used a synchronous request because you did, but you almost certainly should be using an asynchronous request instead (a queue with ASIHTTPRequest).

Took me a while, but you need to use ASIHTTPREQUEST!
- (void)uploadToImageShack {
NSAutoreleasePool *paul = [[NSAutoreleasePool alloc] init];
UIImage *tempImage = self.selectedimage;
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.imageshack.us/upload_api.php"]] autorelease];
NSData *imageData = UIImagePNGRepresentation(tempImage);
[request setFile:imageData withFileName:#"image" andContentType:#"image/png" forKey:#"fileupload"];
[request setPostValue:#"yes" forKey:#"xml"];
[request setPostValue:#"3ZQ7C09K708fce677d9cadee04811cfcbdf63361" forKey:#"key"];
[request setUseCookiePersistence:NO];
[request startSynchronous];
NSError *error = [request error];
if (error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alert show];
[alert release];
}
else if (!error) {
if ([request responseString]) {
parser = [[NSXMLParser alloc] initWithData:[[NSData alloc] initWithData:[request responseData]]];
[parser setDelegate:self];
[parser parse];
}
}
[paul drain];
}

Related

Unable to upload video longer than 1 minute

I am working on application which require a video upload functionality. I am using NSURLRequest for this and its working fine for video which is less then 1 minute in length, but cause problem when video is large. Do any one have any idea about that???
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"----F00";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
fileData = [NSData dataWithContentsOfURL:[mediaDict objectForKey:UIImagePickerControllerMediaURL]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"data[file_name]\"; filename=\"%#\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat: #"Content-Type: %#\r\n\r\n",fileContentType] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:fileData];
[request setHTTPBody:body];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
self.receivedData = [NSMutableData data];
} else {
// Inform the user that the connection failed.
UIAlertView *didFailWithErrorMessage = [[UIAlertView alloc] initWithTitle: #"NSURLConnection " message: #"didFailWithError" delegate: self cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[didFailWithErrorMessage show];
[spinnerView removeFromSuperview];
}
I really appreciate your help friends.
Set the timeout interval and check whether its working or not
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:6000];

Image is not uploading to server

I want to upload an image from device to server. But its not uploading! Even my return success value is showing null. Success value should be either 1 or 0. My code is given here. Please tell me if i am doing any mistakes in my code. Thanks in advance for the help.
-(void)ImageUpload{
NSString *urlString = [NSString stringWithFormat:#"%#upload.php", APIheader];
NSString *postLength = [NSString stringWithFormat:#"%d", [imgDATA length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:urlString]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:imgDATA];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"return string: %#",returnString);
returnString = [returnString stringByReplacingOccurrencesOfString:#"(" withString:#"["];
returnString = [returnString stringByReplacingOccurrencesOfString:#")" withString:#"]"];
returnString = [returnString stringByReplacingOccurrencesOfString:#";" withString:#""];
SBJsonParser *parser = [[SBJsonParser alloc]init];
NSArray *array = (NSArray *)[parser objectWithString:returnString error:nil];
NSString *status = [NSString stringWithFormat:#"%#",[[array objectAtIndex:0]objectForKey:#"success"]];
if ([status isEqualToString:#"1"]) {
NSLog(#"Image Updated");
}
else{
NSLog(#"status is: %#",status);
}
}
[request release];
}
You can use the CoreGraphics' method UIImagePNGRepresentation(UIImage *image), which returns NSData and save it. and if you want to convert it into again UIImage create it using [UIimage imageWithData:(NSData *data)] method. Some Questions related to this post image to server in iphone and
How to convert image into binary format in iOS? as giving the same answer 3 time.
- (void)sendImageToServer {
UIImage *yourImage= [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *postLength = [NSString stringWithFormat:#"%d", [imageData length]];
// Init the URLRequest
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:[NSString stringWithString:#"http://yoururl.domain"]]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:imageData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
// response data of the request
}
[request release];
}
Use this code to upload any image to the server. This works for me. :)
UIImage *yourImage= [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *postLength = [NSString stringWithFormat:#"%d", [imageData length]];
// Init the URLRequest
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:[NSString stringWithString:#"http://yoururl.domain"]]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:imageData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
// response data of the request
}
Try this
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
Note
"BoundaryConstant" is basically the variable "boundary" which is essentially a random (NSString *), "FileParamConstant" is basically your "filename.jpg"
You can also do by importing ASIFormDataRequest calss,Here is the link which tells Why to use this,after downloading classes just do like this,
uploading image to server using ASIFormDataReqest
Hope it will Helps you.....

Switch from Synchronous request to Asynchronous request with image upload?

I need some help, i have been searching around and cant find the correct answer im looking for.
I am uploading images and videos to my server via php, When im uploading the video or image, i want to be able to show a progress view, i have been told that the only way to do this is to use asynchronous instead of synchronous. I have been looking at ways to set up this, but cant really seem to find a good tutorial that will help me with what im trying to accomplish.
Here is some code:
- (void)post:(NSData *)fileData
{
NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:[self saveUserLogin]];
int test;
NSString *string = [array objectAtIndex:3];
test = [string intValue];
test++;
NSData *videoData = fileData;
NSString *urlString = [[NSString alloc]initWithFormat:#"http://www.site.com/members/uploadMovie.php?&username=%#", [array objectAtIndex:0]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *postName = [[NSString alloc]initWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"vid%i.mov\"\r\n", test];
[body appendData:[[NSString stringWithString:postName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:videoData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
NSArray *values = [[NSArray alloc] initWithObjects: [array objectAtIndex:0],[array objectAtIndex:1], [array objectAtIndex:2], [NSString stringWithFormat:#"%i", test], nil];
[values writeToFile:[self saveUserLogin] atomically:YES];
[self.delegate didFinishController:self];
}
this is some code that im using to send a video. filedata is a paramater being passed in with the video data. I want to animate a UIProgressview for the upload progress. I have also heard that apple likes people to use asynchronous anyways. If someone could please help me set up asynchronous instead of what i have, i would be really grateful. Please be specific if you reply, like to what i need to import what delegates, methods. etc.
Thank you very much :)
EDIT:
This is what it looks like now:
- (void)post:(NSData *)fileData
{
NSMutableArray *array = [[NSMutableArray alloc]initWithContentsOfFile:[self saveUserLogin]];
int test;
NSString *string = [array objectAtIndex:3];
test = [string intValue];
test++;
NSData *videoData = fileData;
NSString *urlString = [[NSString alloc]initWithFormat:#"http://www.site.com/members/uploadMovie.php?&username=%#", [array objectAtIndex:0]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *postName = [[NSString alloc]initWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"vid%i.mov\"\r\n", test];
[body appendData:[[NSString stringWithString:postName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:videoData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
//NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
NSLog(#"connected");
responceData = [NSMutableData data];
}
else{
NSLog(#"error");
}
// NSLog(#"%#", returnString);
NSArray *values = [[NSArray alloc] initWithObjects: [array objectAtIndex:0],[array objectAtIndex:1], [array objectAtIndex:2], [NSString stringWithFormat:#"%i", test], nil];
[values writeToFile:[self saveUserLogin] atomically:YES];
// [self.delegate didFinishController:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responceData appendData:data];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSString* responseString = [[NSString alloc] initWithData:responceData encoding:NSUTF8StringEncoding];
NSLog(#"result: %#", responseString);
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"error - read error object for details");
}
NSUrlConnection has an asynchronous request with callbacks.
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest
NSUrlConnection overview:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
That doc also points out you can get an estimation of upload progress by implementing a callback.
connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:
Estimating Upload Progress
You can estimate the progress of an HTTP POST upload with the
connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:
delegate method. Note that this is not an exact measurement of upload
progress, because the connection may fail or the connection may
encounter an authentication challenge.

Blank image with POST

I've an issue with the post of an UIImage on a PHP server, when I post it, the image received is empty.
The method I use is :
- (void)uploadImage {
/*
turning the image into a NSData object
getting the image back out of the UIImageView
setting the quality to 90
*/
NSData *imageData = UIImageJPEGRepresentation(myImage, 0.9);
// setting up the URL to post to
NSString *urlString = #"http://myserver/test.php";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type
You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(returnString);
}
Taken from : http://iphone.zcentric.com/2008/08/29/post-a-uiimage-to-the-web/
Thanks for your help !
I suggest the use of ASIHTTPRequest for this kind of requests. You can do this much more easily with it. Here is an example to how send an image using ASIHTTPRequest:
// Initilize Queue
networkQueue = [[ASINetworkQueue alloc] init];
[networkQueue setUploadProgressDelegate:statusProgressView];
[networkQueue setRequestDidFinishSelector:#selector(imageRequestDidFinish:)];
[networkQueue setQueueDidFinishSelector:#selector(imageQueueDidFinish:)];
[networkQueue setRequestDidFailSelector:#selector(requestDidFail:)];
[networkQueue setShowAccurateProgress:true];
[networkQueue setDelegate:self];
NSData *imageData = UIImageJPEGRepresentation(yourImage, compression);
url = [NSURL URLWithString:#"http://myserver/upload.php"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:#"myImageName" forKey:#"name"];
[request addData:imageData withFileName:#"someFileName.jpeg" andContentType:#"image/jpeg" forKey:#"uploadedImage"];
[networkQueue addOperation:request];
[networkQueue go];
Hope it helps

Post XML data to web server from iphone

i want to post xml data in following format:
<?xml version="1.0" encoding="UTF-8"?>    
                   <data>                                               
                     <email>xyz#domain.com</email>
                             <password>xyz123</password>                                      
                   </data>
and receive in following format from the webserver
<?xml version="1.0" encoding="UTF-8"?>    
<user>
                          <user_id>12</user_id>
                 </user>
help is appreciate
now i am trying to use NSUrlConnection and NSMutableRequest
i can post data on name like form post,but i want to post just xml data.
i have also tried to used ASIHTTPRequest .
any code or link is highly appriciated.
//prepare request
NSString *urlString = [NSString stringWithFormat:#"http://urlToSend.com"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
//set headers
NSString *contentType = [NSString stringWithFormat:#"text/xml"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//create the body
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:#"<xml>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<yourcode/>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"</xml>"] dataUsingEncoding:NSUTF8StringEncoding]];
//post
[request setHTTPBody:postBody];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
NSLog(#"Response: %#", result);
//here you get the response
}
Of course you can also use asynchronous request. Then you have to implement delegate.
Edit. you can also try this:
NSString* boundary = #"---------------------------14737809831466499882746641449";
NSMutableData* postbody = [NSMutableData dataWithCapacity: 200];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", _boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"content.xml\"\r\n", name] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:#"Content-Type: text/xml\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"%#\r\n", val] dataUsingEncoding: NSUTF8StringEncoding]];
NSMutableURLRequest* requestURL= [[[NSMutableURLRequest alloc] init] autorelease];
[requestURL setURL:[NSURL URLWithString: _request.text]];
[requestURL setHTTPMethod:#"POST"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[requestURL addValue:contentType forHTTPHeaderField: #"Content-Type"];
[requestURL addValue: [NSString stringWithFormat:#"%d",[postbody length]] forHTTPHeaderField: #"Content-length"];
[requestURL setHTTPBody: postbody];
and finally i used library from http://allseeing-i.com/ASIHTTPRequest/
and posted from following code:
NSURL *url = [NSURL URLWithString:#"http://url to post data"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:#"test name" forKey:#"name"];
[request setDelegate:self];
[request startSynchronous];
and used delegate method to receive data or error.
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSLog(#"%#",responseString);
// Use when fetching binary data
NSData *responseData = [request responseData];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog(#"Error %#",error);
}