HTTP Post Request from iOS to Django URL - iphone

Essentially this seems to be working however on the server side of things, the Query Dict looks something like this.
POST: QueryDict: {u'Contestant1 John Doe Contestant2 Jane Doe ': [u'']}
which is storing all my values as keys with no values in the Dictionary. Clearly this is a rookie mistake which I'm guessing is on the iOS side of things, so any help would be appreciated. The code is as follows:
NSString *queryString = [NSString stringWithFormat:#"URL HERE"];
NSMutableURLRequest *theRequest=[NSMutableURLRequest
requestWithURL:[NSURL URLWithString:
queryString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[theRequest setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"Contestant1 %# ",contestant1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Contestant2 %# ",contestant2] dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest setHTTPBody:body];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (con) {
NSLog(#"success!");
} else {
//something bad happened
}
EDIT: The solution to my problem.
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:contestant1, #"contestant1",
contestant2, #"contestant2", nil];
NSError *error=nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:postDict
options:NSJSONWritingPrettyPrinted error:&error];
[theRequest setHTTPBody:jsonData];

Related

JSON posting in iOS not working (.NET server)

Posting request to .NET server is not working.
NSDictionary *jsonDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSURL *postURL = [NSURL URLWithString: #"SOME URL"];
NSError *error=nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: postURL
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 60.0];
[request setHTTPMethod: #"POST"];
[request setValue: #"application/json" forHTTPHeaderField: #"Accept"];
[request setValue: #"application/json" forHTTPHeaderField: #"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d",[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
The Output is:
{"CreatedBy":"","EmailAddress":"devanrajupericherl#gmail.com","Zipcode":"","FirstName":"devan","DeviceCategoryID:":"","State":"","CustomerTypeID:":"",..........} like this.....
But it Json object must be:
({CreatedBy:"",EmailAddress:"devanrajupericherl#gmail.com",Zipcode:"",FirstName:"devan",DeviceCategoryID::"",State:"",CustomerTypeID:"" })
I am using .Net server for Posting.
Request is not Posting to the Server. Anyone please help me.
NSString *urlString = #"Your Web Service URL";
NSString *parameterString = #"XYZ";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
// parameter
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"parameter_key\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:parameterString dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// close form
[body appendData:[[NSString stringWithFormat:#"--%#--\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 %#",returnString);

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.....

How to upload image to a url using post request asynchronously?

I have to upload an image to a specific url. The specifications that I have to follow are these:
1. Method should be post
2. Image must be uploaded using multipart HTTP content type
3. The name of the HTTP field should be “uploadingTheFile”.
4. Multipart data shiuld have filename.
5. Image content type should be among following-jpeg,jpg,png,gif
I want to upload using NSURLConnection asynchronously. I think I am not able to set the parameters in the request in a proper way.I am getting status code as 200 which suggests that there is no problem with my NSURLConnection delegate methods. The code that I am trying is :
NSString *stringBoundary=#"0xKhTmLbOuNdArY";
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#",stringBoundary] forHTTPHeaderField:#"uploadfile"];
NSMutableData *postBody = [NSMutableData data];
NSData *imageData=UIImagePNGRepresentation([UIImage imageNamed:#"IMG_0215.JPG"]);
//[postBody appendData:imageData];
[postBody appendData:[#"Content-Disposition: form-data; name=\"data;filename=\"media.png\"\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:imageData]];
[postBody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postBody];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
self.data = [NSMutableData data];
}
I am using following code and it is working fine for me.
NSData *imageData = UIImageJPEGRepresentation(empImgView.image, 90); // convert image in NSData
NSString *urlString = #"http://abc.com/saveimage/Default.aspx"; // your url
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 *imgNameString = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.jpg\"\r\n",[responseSrting substringWithRange:NSMakeRange(1, responseSrting.length - 2)]];
[body appendData:[[NSString stringWithString:imgNameString] 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]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#",returnString);
Here you can learn how to use afnetworking for upload images
https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ
You can use AFNetworking (it is opensource), here is code that worked for me. This is for AFNetworking 3.0 version.
NSString *serverUrl = [NSString stringWithFormat:#"http://www.yoursite.com/uploadlink", profile.host];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:serverUrl parameters:nil error:nil];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURL *filePath = [NSURL fileURLWithPath:[url path]];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
LLog(#"progres increase... %# , fraction: %f", uploadProgress.debugDescription, uploadProgress.fractionCompleted);
});
} completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];

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);
}

Issue with uploading a video file using HTTP Post from iPhone app to server:

I am trying to upload a .3gp video file into my server using HTTP post method from my iPhone app to my server. 3gp video file is available in my project resource. I use the following code for that,
-(IBAction)buttonAction
{
NSMutableURLRequest* post = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: #"http://115.111.27.206:8081/vblo/upload.jsp"]];
[post setHTTPMethod: #"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------358734318367435438734347"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[post addValue:contentType forHTTPHeaderField: #"Content-Type"];
body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Disposition: form-data; name=\"videofile\"; filename=\"video.3gp\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[[NSBundle mainBundle] pathForResource:#"video" ofType:#"3gp"]
dataUsingEncoding: NSASCIIStringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[post setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:post returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
// Just to show the response received from server in an alert...
UIAlertView *statusAlert = [[UIAlertView alloc]initWithTitle:nil message:(NSString *)returnString delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:#"ok", nil];
[statusAlert show];
}
This code doesn't do anything.
Could someone guide me what's wrong?
UPDATED:
I saw an example from the link -> iphone.zcentric.com/page/2 there are using "iphone.zcentric.com/test-upload.php"; PHP to upload and in my code i use JSP "115.111.27.206:8081/vblo/upload.jsp"; to upload to my server. Is this anything wrong here?
Thanks.
I suggest the following sample code. The multipart is not required if you send one single body - in this case the video. I would recommend binary encoding instead of any other character encoding for speed and preserve binary data integrity.
NSMutableURLRequest* post = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: #"http://115.111.27.206:8081/vblo/upload.jsp"]];
[post setHTTPMethod: #"POST"];
[post addValue:#"video/3gpp" forHTTPHeaderField:#"Content-Type"];
body = [[NSData alloc] initWithContentOfFile:[[NSBundle mainBundle] pathForResource:#"video" ofType:#"3gp"]];
[post setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:post returningResponse:nil error:nil];
[post release];
Good luck!
As it looks like you are faking being a form I would recommend using ASIFormDataRequest
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addData:videoData withFileName:#"videofile.3gp" andContentType:#"video/3gpp" forKey:#"video"];
Maybe you should have a look at the response and - maybe - the Error:
NSError *error;
NSURLResponse *response;
NSData *returnData = [NSURLConnection sendSynchronousRequest:post
returningResponse:response error:error];
if (returnData==nil) {
/* Edit this or set Breakpoint */
NSLog(#"Ups... Response: %# Error: %#",response,error);
}