This is my code which uses POST request to retrieve data but i am not able to get the desired results. There is no problem in url because it is showing JSON output on browser.
NSString *urlString = #"my url string";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"email_string\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n",allIOSContactsEmailAddresses] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data!=nil)
{
NSArray* array=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"array=%#",array);
}
}];
it is showing array=(null) in console..
Your multipart message body is not properly setup.
After the last part (you have only one) there needs to be a "close-boundary-delimiter". So, before you set the body for the request, you need to append the delimiter:
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
Strictly, there's no need to close the "close-boundary-delimiter" with a CRLF ("\r\n").
There is no need to prepend the actual body value (allIOSContactsEmailAddresses) with a CRLF (you did not). This CRLF would count as body content. Actually, this can confuse the consumer.
Contrary, for text bodies, a closing CRLF may sometimes needed (depends on the server).
Note when adding a header, it must be closed with a CRLF (as you did). In order to close the header area a closing CRLF is required. Regarding this, your message is correct.
I just tried to use your code, and it succeeded without any problem.
Therefore your problem is in the server you send the request to, or in your NSURLConnection delegate methods which are not implemented properly.
You should also post the sending code (NSURLConnection usage).
Related
I'm working on uploading an image to a server from last two days as there are tons of questions about uploading an image through AFNetworking and NSURLSession and other methods of uploading all I'm asking is I didn't found a single answer explaining the whole concept about how the things work and what is going on under the hood I searched youtube also all the stuff are available in Swift and trust me no Explanation at all and from my result I found this answer is something that looks familiar to me
//Init the NSURLSession with a configuration
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
//Create an URLRequest
NSURL *url = [NSURL URLWithString:#"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
//Create POST Params and add it to HTTPBody
NSString *params = #"api_key=APIKEY&email=example#example.com&password=password";
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
//Create task
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
}];
[dataTask resume];
and also the most popular answer about this topic is by User XJones is:-
Here's code from my app to post an image to our web server:
// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:[NSString stringWithString:#"1.0"] forKey:[NSString stringWithString:#"ver"]];
[_params setObject:[NSString stringWithString:#"en"] forKey:[NSString stringWithString:#"lan"]];
[_params setObject:[NSString stringWithFormat:#"%d", userId] forKey:[NSString stringWithString:#"userId"]];
[_params setObject:[NSString stringWithFormat:#"%#",title] forKey:[NSString stringWithString:#"title"]];
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = [NSString stringWithString:#"----------V2ymHFg03ehbqgZCaKO6jy"];
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = [NSString stringWithString:#"file"];
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#""];
// 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=%#", BoundaryConstant];
[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", BoundaryConstant] 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", BoundaryConstant] 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];
But my point is I'm learning on my own and it is very difficult to understand for the beginner without explanation so All I'm asking is an explanation, an Detail explanation about the whole process if someone have a hard time to spend on this question because believe it or not I found this the hardest topic till now because the main reason is there are no tutorials about the whole process and also no explanation at all for beginners if someone can a step now and explain the concept it'll be easier to the students who will learn tomorrow. So anybody who can explain this in detail and how the uploading process works and some steps for the reference will be greatly appreciated.
Note : Consider I Have an API and a Key "image" .
here we gonna look at image uploading along with some **parameters because most of time we upload image along with some parameters such as userId.
Before going deep into our topic let me provide the code for doing the stuff source,All the details we gonna see below are from some other stack overflow threads and some from other sites,i'll provide all the links for your reference.
-(void)callApiWithParameters:(NSDictionary *)inputParameter images:(NSArray *)image imageParamters:(NSArray *)FileParamConstant{
//1
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
//2
NSString *boundary = #"------CLABoundaryGOKUL";
//3
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
//4
NSMutableData *body = [NSMutableData data];
for (NSString *key in inputParameter) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [inputParameter objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
}
for (int i = 0; i < image.count; i++) {
NSData *imageDatasss = UIImagePNGRepresentation(image[i]);
if (imageDatasss)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant[i]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageDatasss];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//5
[request setHTTPBody:body];
//6
[request setURL:[NSURL URLWithString:#"http://changeThisWithYourbaseURL?"]];//Eg:#"http://dev1.com/PTA_dev/webservice/webservice.php?"
//7
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
//8
if ([httpResponse statusCode] == 200) {
NSDictionary * APIResult =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(#"Response of %#: %#",[inputParameter valueForKey:#"service"],APIResult);
}else{
//9
NSLog(#"%#",error.localizedDescription);
}
}];
}
NOTE: Since it is a broad topic i have provided documentation link for detail info.
We are using ** NSMutableURLRequest** instead of ** NSURLRequest** because we gonna append some data to it.if you need some deep clarification about mutable url request go through this documentation.
setHTTPShouldHandleCookies here we have to decide whether we are going to use cookies or not.To know more about visit
setTimeoutInterval this helps to set a time limit to url request.Add time interval in seconds after the given time,request will be terminated.
setHTTPMethod there are many methods.But we use GET and POST methods in many cases.Difference between POST and GET is here and here
Boundary helps in separating the parameters from each other,so that the server can identify them.The boundary may be anything as your wish feel free to edit it.
Here we use multipart/form-data; boundary= as content type.To know why we are going to this content type look into this thread.
NSMutableData * body we gonna append all the parameters and values to this data and later setHTTPBody to the UrlRequest.
If this is how we call the 'callApiWithParameters' method
- (IBAction)Done:(id)sender{
NSDictionary * inputParameters = [NSDictionary dictionaryWithObjectsAndKeys:
#"1",#"user_id" ,
"XXX",#"name" ,
nil];
NSArray * image = [NSArray arrayWithObjects:[UIImage imageNamed:#"Test"],[UIImage imageNamed:#"Test1"],nil];
NSArray * imageParameters = [NSArray arrayWithObjects:#"img_one",#"img_two",nil];
[self callApiWithParameters:inputParameters images:image imageParamters:imageParameters];
}
then the data (i.e body) will look like this
Content-Type=multipart/form-data; boundary=------CLABoundaryGOKUL
--------CLABoundaryGOKUL
Content-Disposition: form-data; name=user_id
1
--------CLABoundaryGOKUL
Content-Disposition: form-data; name=name
XXX
--------CLABoundaryGOKUL
Content-Disposition: form-data; name=img_one; filename=image.jpg
Content-Type:image/jpeg
//First image data appended here
--------CLABoundaryGOKUL
Content-Disposition: form-data; name=img_two; filename=image.jpg
Content-Type:image/jpeg
//Second image data appended here.
The above give data will clearly explain what going on,all the parameters and keys have been append in the data Here you can find more details about sending multipart/form.
Now simply add the above data to request by [request setHTTPBody:body];
setURL in this method add your base url of your app.
Now all we need to do is make a connection to the server and send the request.Here we use NSURLConnection to send request.Description about NSURLConnection Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.
statusCode which helps to find out whether we got successful response from server. If 200 means OK, 500 means Internal Server Error, etc.. more details here .
Handle the error in else case.
FYI I have explained what i can,refer the links for better understanding.
EDIT:
Just change the name in imageParamater array,To satisfy your requirement changed img_one & img_two with image.
- (IBAction)Done:(id)sender{
//Change input parameters as per your requirement.
NSDictionary * inputParameters = [NSDictionary dictionaryWithObjectsAndKeys:
#"1",#"user_id" ,
"XXX",#"name" ,
nil];
NSArray * image = [NSArray arrayWithObjects:[UIImage imageNamed:#"Test"],nil]; //Change Test with your image name
NSArray * imageParameters = [NSArray arrayWithObjects:#"image",nil];//Added image as a key.
[self callApiWithParameters:inputParameters images:image imageParamters:imageParameters];
}
and Change Point 6 with your example base URL,
//6
[request setURL:[NSURL URLWithString:#"http://google.com/files/upload.php?"]];
I think it's Helpful for you...
- (void)sendImageToServer
{
UIImage *yourImage= [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *base64 = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSString *strImage = [NSString stringWithFormat:#"data:image/png;base64,%#",base64];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:strImage,#"image", nil];
NSError * err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&err];
NSString *UserProfileInRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *data=[UserProfileInRequest dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *len = [NSString stringWithFormat:#"%ld", (unsigned long)[data length]];
// Init the URLRequest
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] init];
[req setURL:[NSURL URLWithString:#"http://YOUR_URL"]];
[req setHTTPMethod:#"POST"];
[req setValue:len forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:data];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:req completionHandler:^(NSData *dt, NSURLResponse *response, NSError *err){
//Response Data
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:dt options:kNilOptions error:&err];
NSLog(#"%#", [dic description]);
}]resume];
}
Use AFNetworking For this task which will give very easy and reliable solution.
My question could be marked as duplicate but after going through tons of solutions I am still not able to figure out where am i going wrong. Please help.
Name of my image is 'image.png'.Please do specify what should be included in BoundaryConstant. I have just copied it from some site.
// // create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL* requestURL = [NSURL URLWithString:#"http://....."];
[request setURL:requestURL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
NSString *filename = #"image";
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add image data
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:#"image.png"]);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.png\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Ret: %#",returnString);
There are extra \r\n characters (see point 2 below), but it otherwise looks OK. Without seeing the server code, nor the NSURLResponse object, nor the NSError object, we can't diagnose what might be going wrong.
A few details:
I would not include dashes at the start of the boundary. If nothing else, it makes it really hard to differentiate the leading -- from the actual boundary.
You are writing an extra \r\n before the boundaries. I'd replace
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
with
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
And replace
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
with
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
As it is (in particular, where you added the image data, a \r\n, and then \r\n--%#--\r\n), you're adding an extra two bytes (namely, \r\n) to the end of the uploaded image. This is generally doesn't cause problems (the image generally still works), but it is not correct.
You generally don't have to set the Content-Length header.
Do not use synchronous requests. Use sendAsynchronousRequest.
You are using nil for response and error objects. If you do that, you are extremely limited as to what diagnostics you can perform. You are flying blind. One should always examine the resulting NSURLResponse and NSError objects.
We cannot tell whether this upload would work without seeing the server code. In particular, I find your use of a variable named filename with a value of of image as the name of the field as a little confusing. But if your $_FILES on the server (or if not using PHP, whatever field name its looking for) is looking for image, that's fine. It's just a confused/misleading choice of variable name. I'd probably call that variable fieldName or something like that.
Most importantly, is $_FILES looking for a field name called image?
You have a line that says:
[body appendData:[NSData dataWithData:imageData]];
That could just be:
[body appendData:imageData];
No need to create new NSData.
I'd remove that second call to setURL. That isn't necessary.
You are loading image.png, converting it to a UIImage and then using UIImagePNGRepresentation to get NSData. That can work but is very inefficient. Just load the contents of the file into NSData directly, bypassing UIImage altogether.
Also, I'd suggest you log an error message if the image is not found. Right now, it will simply skip the step of adding the image (meaning that it will silently send the request, not telling you if there was a problem).
You should watch this request in a tool like Charles. If you're going to get in this level of detail in preparing requests, you should inspect the requests as they go out.
I'd suggest you just use something like AFNetworking which gets you out of these sorts of weeds. If you want to do this yourself, see https://stackoverflow.com/a/24252378/1271826.
I'm trying to upload a file to OneDrive using BITS protocol. The documentation describes a request to be like this:
The complete documentation page is here:OneDrive Large File Uploads
Actually it deals with uploading files by chunks but since a size of chunk must be not greater than 60 MB I'm trying to upload a small file as a single chunck. Here's my code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"download" ofType:#"jpeg"];
self.data = [NSData dataWithContentsOfFile:path];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: attachment; name=\"image\"; filename=\"image.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:self.data]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
length = body.length;
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlString]];
urlRequest.HTTPMethod = #"POST";
[urlRequest setValue:#"BITS_POST" forHTTPHeaderField:#"X-Http-Method-Override"];
[urlRequest setValue:self.accessToken forHTTPHeaderField:#"Authorization"];
[urlRequest setValue:self.sessionId forHTTPHeaderField:#"BITS-Session-Id"];
[urlRequest setValue:#"Fragment" forHTTPHeaderField:#"BITS-Packet-Type"];
[urlRequest setValue:[NSString stringWithFormat:#"%d", length] forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:[NSString stringWithFormat:#"0-%d/%d", length - 1, length] forHTTPHeaderField:#"Content-Range"];
urlRequest.HTTPBody = body;
self.uploadConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
Whatever I try I receive 400 error and BadArgument as X-ClientErrorCode. Parameters self.accessToken and self.sessionId are valid, they are just received from the SDK. I have no idea what's wrong there. Can anyone please help me? What might I be doing wrong?
The issue was the "Content-Range" was incorrect - it needed to include "bytes" in front of the range.
Original Answer
It doesn't look like you're sending either the Create-Session request before the Fragment, nor the Close-Session request after the Fragment. You'll need to create the session before sending fragments even if you're only planning on sending a single one. If you know you'll only be sending a single fragment it's better to use a direct upload to avoid unnecessary round trips:
http://msdn.microsoft.com/en-US/library/dn659726.aspx#upload_a_file
In my iOS app I am posting json string to server using NSURLConnection like this.
post_string = #"{"function":"getHuddleDetails", "parameters": {"user_id": "167","location_id": "71","huddle_id": "328","checkin_id": "1287"},"token":""}"
-(void)myServerRequests:(NSString *)post_string{
NSData *postData = [post_string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.myServerURl.com/jsonpost"]];
[request setTimeoutInterval:100];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
webData = [[NSMutableData alloc]init];
}
}
And posting multipart/form-data (not JSON) using NSURLSession using below code
-(void)myFunction:(NSString *)user_name paswd:(NSString *)pass_word {
NSString *boundary = [self boundaryString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.myServerURl.com/formpost"]];
[request setHTTPMethod:#"POST"];
[request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary] forHTTPHeaderField:#"Content-Type"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"username\"\r\n\r\n%#", user_name] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"password\"\r\n\r\n%#", pass_word] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:postbody completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSAssert(!error, #"%s: uploadTaskWithRequest error: %#", __FUNCTION__, error);
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
}];
[task resume];
}
This works perfectly fine with NSURLSession, but when I tried to post json string (converted it to NSDATA and posted using NSURLSession), it is not working.
Why it happens ?
Thanks in advance
If you want to send JSON to a server you should set the content type accordingly to application/json and your content is actually just that: the JSON encoded preferably in UTF-8.
In your method myServerRequests: you set content type application/x-www-form-urlencoded - but you don't setup the corresponding content correctly. How to do this can be read here: URL-encoded form data. Additionally, specifying a charset parameter has no effect at all.
In case you want to send a string parameter for a application/x-www-form-urlencoded content type, you should also not use a lossy conversion. Instead use UTF-8. Note that NSStrings length returns the number of UTF-16 code points - which is not the same as the number of bytes of an UTF-8 encoded string.
Recap:
Don't use application/x-www-form-urlencoded content type. Instead:
Content-Type = application/json
Content-Length = <length in bytes of the UTF-8 encoded JSON>
When you fix these issues, the request should be OK.
When using a multipart/form-data request I strongly recommend to use a network library. Doing this by hand is too error prone and you would need to read at least 300 RFCs to know that you are doing it correctly ;)
I found few snippet from online to upload image from iphone to the server folder, it's showing to use server side scripting eg. use php at server side
<?php
$uploaddir = 'uploads/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "Uploaded!";
}else{
echo "Not Uploaded!";
}
/>
is it any possibilites to upload image directly to the server folder without the above code,
let say I want to upload into http://111.22.333.44/mysite/pics/ w/o any server side scripting, if can how this can be done
/*
turning the image into a NSData object
getting the image back out of the UIImageView
setting the quality to 90
*/
NSData *imageData = UIImageJPEGRepresentation(image.image, 90);
// setting up the URL to post to
NSString *urlString = #"http://iphone.zcentric.com/test-upload.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);
this code will be helpful for you....
If you setup your webserver to allow the PUT method you could do this. 99% of web servers only allow the GET and POST methods.
Having never done that, I can't give you much help. Here is a page that I got from google talking about it:
http://www.w3.org/QA/2008/10/understanding-http-put.html