image base64 corrupt post (Objective-C) - objective-c

I'm trying to send a post with several parameters and include an image in base64.
The image coding does it well, I checked the base64 image in a online base64 to image converter and looks like the image is encoded successfully. I can do the post process without any problem, but when I download it, the log shows this error:
Error: ImageIO: JPEG Corrupt JPEG data: 120 extraneous bytes before
marker 0xf1
Error: ImageIO: JPEG Unsupported marker type 0xf1
I do this in a method
jpgData = UIImageJPEGRepresentation(image, 0.1f);
imageString = [jpgData base64EncodedStringWithOptions:0];
And this is the method that sends the post, which is where I think the error is.
- (void)putComment{
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
__block int responseCode = 0;
dispatch_async(backgroundQueue, ^{
NSString *requestParams = [NSString stringWithFormat:
#"idAdvertiser=%#&idUserDevice=%#&image=%#&text=%#&userName=%#&groups=%#",
ADVERTISER_ID, idUserDevice, imageString, texto, userName, groups];
[requestParams stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
NSData *postData = [requestParams dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
// NSData *postData = [requestParams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLenght = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest new];
[request setURL:[NSURL URLWithString: URL_COMMENT]];
[request setHTTPMethod:#"POST"];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setValue:postLenght forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
[request setTimeoutInterval:40];
NSError *error = nil;
NSHTTPURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest: request
returningResponse: &response
error: &error];
});
}
The server side works perfectly (tested in an Android app), so the problem is not server related.

You encode your url so no need for this line:
[requestParams stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"];
Remove it and try again.
Also
[request setURL:[NSURL URLWithString: URL_COMMENT]];
can be turned to:
[request setURL:[NSURL URLWithString: [URL_COMMENT stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];

Related

POST form data in Objective C

I have to pass form data in body part. here is postman screen short for better understanding.
body part
content type
here is my code what I had try.
NSString *Accesstoken = [NSString stringWithFormat:#"Bearer %#",tokenInfo.access_token];
// parameter is String object : "user_id=18&deal_id=218"
//NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"user_id", #"18487",
#"deal_id", #"218",
nil];
// NSError *errorr;
// NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&errorr];
[request setValue:Accesstoken forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// NSData *postData = [parameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
// [request setHTTPBody:postData];;
// [request setHTTPBody:[parameter dataUsingEncoding:NSUTF8StringEncoding]];
// [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:#{#"user_id":#"18487",#"deal_id":#"218" } options:0 error:nil]];
for above code I am getting http status code : 404 its wrong. and when I try in postman I am getting 401 its perfect I want that. Please help Thanks.
Just export the request from POSTMAN in objective-C : https://www.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets

post request to server does not send the content of textfields?

I'm trying to send the content of my textfields firstname and lastname with my button sendpost to my php server. Once I run my app and fill my textfields with some random text and press send, I receive an e-mail on my server but there is no content.
(void) sendAction{
NSError *error = nil;
NSString *postparams = [NSString stringWithFormat:#"info=%#_%#",firstname.text,lastname.text];
NSData * postdata = [postparams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString * postlength= [NSString stringWithFormat:#"%d",[postdata length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://faketest.com/test/mail.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postdata];
NSData * rawdata = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSString *rawdatastring =[[NSString alloc]initWithData:rawdata encoding:NSUTF8StringEncoding];
NSLog(#"%#",rawdatastring);
}
I believe it may be because you're using a "Current-Type" header, instead of the usual "Content-Type" header. Try the following and see if it solves the problem:
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];

Getting Black Image on server side after posting through Json parsing

thanks in Advance..
In my app, i have to upload an image to the server, below is my code. code is working properly, as i get the response but problem is that, on server side image is just black.
sessionid=[[[NSUserDefaults standardUserDefaults] valueForKey:#"SessionID"]objectAtIndex:0];
NSLog(#" ID = %#",sessionid);
NSData *da = [NSData data];
da = UIImagePNGRepresentation(self.Profilepic);
NSString *imgStr = [da base64Encoding];
NSLog(#" %d", imgStr.length);
NSString *serverscriptpath=[NSString stringWithFormat:#"http://c4ntechnology.com/biker/web_services/ws_insert_register3.php?"];
NSString *post =[[NSString alloc] initWithFormat:#"profile_pic=%#&sessionid=%#",imgStr,sessionid];
NSLog(#"post string is :%#",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"post length is :%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *script_path=[NSString stringWithFormat:#"%#",serverscriptpath];
[request setURL:[NSURL URLWithString:script_path]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"%#",script_path);
NSData *serverReply = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString* responseString = [[[NSString alloc] initWithData:serverReply encoding: NSUTF8StringEncoding] autorelease];
NSDictionary *dict = [responseString JSONValue];
NSLog(#"%#",dict);
[self ReceivedResponse:dict];
-(void)ReceivedResponse:(NSDictionary *)d
{
[AlertHandler hideAlert];
NSLog(#"%#",d);
}
please any one can help me to find out problem, that why on server image is black.?
i am using NSDatAdditions.h file for converting into base64.
when i am using
NSData *imageData = UIImageJPEGRepresentation(Profilepic, 1.0);
at server side, file is not supported occurring, so i used
NSData *da = [NSData data];
da = UIImagePNGRepresentation(self.Profilepic);
You should try using NSUTF8StringEncoding instead of NSASCIIStringEncoding (unless you're sure that the web-server uses ASCII encoding).
If this doesn't work, I'd try the followings:
Encode image as base 64, and afterwards decode it and check if the result is ok.
If 1 passes, check exactly what the server receives (should be the same base64 string as you've sent, otherwise there's probably an issue with different encodings)
As a side note, da = [NSData data]; is useless, since you overwrite it right after, use directly NSData *da = UIImagePNGRepresentation(self.Profilepic);

connection failed : Bad Url (null) error while sending POST data from Xcode to classic ASP page.

In my iphone project, I need to pass member Id and pwd to a web server. I have tried my code with Synchronous as well as asynchronous request but I always get error : connection failed: Bad URL (null). can any one please help me to find what's wrong with the code?
My code:
NSString *post =[NSString stringWithFormat:#"memberId=%#&pwd=%#",txtUName.text,txtPwd.text];
NSLog(#"%#",post);
NSURL *url = [NSURL
URLWithString:#"http://testweb.talkfusion.com/videocenter/xlogin.asp%#"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
//set up the request to the website
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
The %# at the end in your url is wrong. POST-data are not part of the url.

Put JSON encoded array as NSData from NSURLResponse into NSArray

I'm unable to get this to work:
NSString *post = [NSString stringWithFormat:#"userudid=%#", [udid stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",post);
NSData *postData = [NSData dataWithBytes:[post UTF8String] length:[post length]];
//[udid dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSLog(#"%#",postData);
//NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.myserver.com/myapp/readtags2.php"]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
//[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSString *content = [NSString stringWithUTF8String:[urlData bytes]];
NSLog(#"responseData: %#", content);
is the POST formed correctly? Because i can get it to work from a manual html form posting to the same php file, but i get nothing back when doing it from iOS
You might have an easier time doing HTTP POST's with ASIHTTPRequest.
Form-Posting with ASIHTTPRequest is explained in the section titled "Sending a form POST with ASIFormDataRequest" here: http://allseeing-i.com/ASIHTTPRequest/How-to-use
Otherwise, have a look at the NSURLResponse, check the response code and see if iOS thinks the POST was successful.
Other thing you can use to check is a tool like wireshark to compare the network traffic from your web-based form POST to the traffic from your iOS POST. It looks like you're doing it right, but the best way to be sure is something like wireshark.