How send text to HTTP POST? - ios

In my app I am using this code for sending parameters name, email, website url and comment in blog...Probably some value are wrong setting...Someone can help me solved? I'm going crazy!! Thanks in advance!
-(void)invia{
[self.connessione cancel];
NSURL *indirizzo = [NSURL URLWithString:#"http://*********ina.altervista.org/********/feed/"];
//initialize a request from url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[indirizzo standardizedURL]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setHTTPMethod:#"POST"];
NSDictionary *parametri = [NSDictionary dictionaryWithObjectsAndKeys:
campoSito.text, #"url",
campoNome.text, #"author",
campoEmail.text, #"email",
campoCommento.text, #"content", nil];
NSString *dati_postati=[NSString stringWithFormat:#"%#",parametri];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[dati_postati dataUsingEncoding:NSUTF8StringEncoding]];
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connessione = connection;
//start the connection
[connection start];
[self dismissViewControllerAnimated:YES completion:nil];
campoCommento.text=nil;
campoEmail.text=nil;
campoSito.text=nil;
campoNome.text=nil;
}
EDIT:
#Rich I've tried to read the API documentation for the web service, more precisely the part which concern "Create a Comment on a Post",I think my site ID concern the article is "gnutella"...I do not think there is a numeric id...from which I extract the id?
UPDATE:
I've extract Post ID from article...is 1757
I've tried with this URL without success
NSURL *indirizzo = [NSURL URLWithString:#"http://zenzeroincucina.altervista.org/gnutella/1757/"];
NSURL *indirizzo = [NSURL URLWithString:#"http://zenzeroincucina.altervista.org/gnutella/1757/replies/new"];
NSURL *indirizzo = [NSURL URLWithString:#"http://zenzeroincucina.altervista.org/wp-admin/post.php?post=1757&action=edit"];
Another code method:
#define kSendCommentJSON #"?json=respond.submit_comment"
NSURL *completeURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://zenzeroincucina.altervista.org/gnutella/feed/"]];
AFHTTPClient *httpClient = [AFHTTPClient clientWithBaseURL:completeURL];
NSDictionary *parametri = [NSDictionary dictionaryWithObjectsAndKeys:
campoSito.text, #"url",
campoNome.text, #"author",
campoEmail.text, #"email",
campoCommento.text, #"content", nil];
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"" parameters:parametri constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Completed Successfullly");
//[self commentPostSuccess];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failed misurable %#", [error description]);
//[self commentPostFailed];
}];
[operation start];
I've tried with this method...not yet!!
Console return successfully but text is not sent correctly...
Also tested on device(for exclusion a possible bug)...nothing!

You need to send the parameters correctly in the format key=value&key=value, not just as description of a NSDictionary.
NSDictionary *parametri = [NSDictionary dictionaryWithObjectsAndKeys:
campoSito.text, #"url",
campoNome.text, #"author",
campoEmail.text, #"email",
campoCommento.text, #"content", nil];
NSMutableArray *values = [NSMutableArray new];
[parametri enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
// Create an encoded parameter pair -> k=v
NSString *p = [NSString stringWithFormat:#"%#=%#", key, [[obj description] stringByAddingPercentEscapesUsingEncoding:NSUTF8Encoding]];
[values addObject:p];
}];
NSString *dati_postati = [values componentsJoinedByString:#"&"];
UPDATE:
So after looking at the POST request that is sent (on this page:
HTTP POST http://zenzeroincucina.altervista.org/wp-comments-post.php
Host: zenzeroincucina.altervista.org
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:28.0) Gecko/20100101 Firefox/28.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://zenzeroincucina.altervista.org/gnutella/
Cookie: __cfduid=d1ef25815caa898a777114c04c4d37bfc1398261681664; av_device_cookie=computer; av_mobile_cookie=desktop; PHPSESSID=b27e99a06qrkkd2lenppt9p1i6; __utma=178781179.1711693902.1398262580.1398262580.1398262580.1; __utmc=178781179; __utmz=178781179.1398262580.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 201
author=Test&email=test%40stack.com&url=stackoverflow.com&comment=Test&captcha_code=dw3P&submit=Submit+Comment&comment_post_ID=1757&comment_post_ID=1757&comment_parent=0&akismet_comment_nonce=f8393add8f
This doesn't massively help however as you need to include the captcha.
What you want to use is the WordPress API for posting comments. I played around with this but I don't have your site ID.

Try this out:
-(void)invia{
[self.connessione cancel];
NSString *param = [NSString stringWithFormat:#"url=%#&author=%#&email=%#&content=%#",campoSito.text,campoNome.text,campoEmail.text,campoCommento.text];
NSURL *indirizzo = [NSURL URLWithString:[NSString stringWithFormat:#"http://*********ina.altervista.org/********/feed?%#",param]];
//initialize a request from url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[indirizzo standardizedURL]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setHTTPMethod:#"POST"];
NSString *dati_postati=[NSString stringWithFormat:#"%#",parametri];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[dati_postati dataUsingEncoding:NSUTF8StringEncoding]];
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
self.connessione = connection;
//start the connection
[connection start];
[self dismissViewControllerAnimated:YES completion:nil];
campoCommento.text=nil;
campoEmail.text=nil;
campoSito.text=nil;
campoNome.text=nil;
}

Related

Upload image to the PHP server from iOS

I know this question has been asked earlier as well but my issue is a bit different.
I want to upload an image to the PHP server and i want to send more parameters along with an image from an iOS.
I searched on the google and found two solutions:
Either we will send an image as Base64 encoded string in JSON. Referred link.
Or we will upload an image to server using form data. I have referred this link. If someone refers me this way, then please help me to add more parameters in this API.
Now my question is, which one is the best way to upload an image to the server and i have to send more parameters (username, password and more details) in the same web service call.
Thanks in advance.
You can upload image from iOS App to PHP server like this two way:
Using New AFNetworking :
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
NSString *stringUrl =#"http://www.myserverurl.com/file/uloaddetails.php?"
NSString *string =#"http://myimageurkstrn.com/img/myimage.png"
NSURL *filePath = [NSURL fileURLWithPath:string];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:userid,#"id",String_FullName,#"fname",String_Email,#"emailid",String_City,#"city",String_Country,#"country",String_City,#"state",String_TextView,#"bio", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:stringUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileURL:filePath name:#"userfile" error:nil];//here userfile is a paramiter for your image
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"%#",[responseObject valueForKey:#"Root"]);
Alert_Success_fail = [[UIAlertView alloc] initWithTitle:#"myappname" message:string delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[Alert_Success_fail show];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
Alert_Success_fail = [[UIAlertView alloc] initWithTitle:#"myappname" message:[error localizedDescription] delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[Alert_Success_fail show];
}];
Second use NSURLConnection:
-(void)uploadImage
{
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *urlString = [ NSString stringWithFormat:#"http://yourUploadImageURl.php?intid=%#",1];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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]];
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#\"\r\n", 1]] 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];
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
This both way working fine for uploading image from app to php server hope this helps for you.
Using AFNetworking this is how I do it:
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setObject:#"myUserName" forKey:#"username"];
[params setObject:#"1234" forKey:#"password"];
[[AFHTTPRequestOperationLogger sharedLogger] startLogging];
NSData *imageData;
NSString *urlStr = [NSString stringWithFormat:#"http://www.url.com"];
NSURL *url = [NSURL URLWithString:urlStr];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
imageData = UIImageJPEGRepresentation(mediaFile, 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:nil parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFileData:imageData name:#"mediaFile" fileName:#"picture.png" mimeType:#"image/png"];
}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"File was uploaded" message:#""
delegate:self cancelButtonTitle:#"Close" otherButtonTitles: nil];
[alert show];
}
failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON)
{
NSLog(#"request: %#",request);
NSLog(#"Failed: %#",[error localizedDescription]);
}];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
{
NSLog(#"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
Try with Restkit
Here is link Restkit image upload with parameter
You can get Restkit help from here Restkit integration step
Try this.
-(void)EchoesPagePhotosUpload
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
[self startIndicator];
});
//NSLog(#"%#",uploadPhotosArray);
NSMutableArray *uploadPhotosByteArray=[[NSMutableArray alloc] init];
conversionImage= [UIImage imageWithContentsOfFile:[uploadPhotosArray objectAtIndex:0]];
NSLog(#"conversionImage.size.height %f",conversionImage.size.height);
NSLog(#"conversionImage.size.width %f",conversionImage.size.width);
if(conversionImage.size.height>=250&&conversionImage.size.width>=250)
{
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self performSelectorInBackground: #selector(LoadForLoop) withObject: nil]; NSLog(#"conversionImage.size.height %f",conversionImage.size.height);
NSLog(#"conversionImage.size.width %f",conversionImage.size.width);
for(int img_pos=0;img_pos<[uploadPhotosArray count];img_pos++)
{
conversionImage= [UIImage imageWithContentsOfFile:[uploadPhotosArray objectAtIndex:img_pos]];
NSData *imageData = UIImageJPEGRepresentation(conversionImage,1.0);
[Base64 initialize];
NSString *uploadPhotoEncodedString = [Base64 encode:imageData];
//NSLog(#"Byte Array %d : %#",img_pos,uploadPhotoEncodedString);
[uploadPhotosByteArray addObject:uploadPhotoEncodedString];
}
dispatch_async(dispatch_get_main_queue(), ^{
NSString *photo_description=[webview stringByEvaluatingJavaScriptFromString: #"document.getElementById('UploadPicsDesc').value"];
NSString *uploadPhotoImageName=#"uploadPhoto.jpg";
NSDictionary *UploadpicsJsonResponseDic=[WebserviceViewcontroller EchoesUploadPhotos:profileUserId imageName:uploadPhotoImageName Image:uploadPhotosByteArray PhotoDescription:photo_description];
//NSLog(#"%#",UploadpicsJsonResponseDic);
NSString *UploadPhotosStatusString=[UploadpicsJsonResponseDic valueForKey:#"Status"];
NSLog(#"UploadPhotosStatusString :%#",UploadPhotosStatusString);
NSString *uploadPhotosCallbackstring=[NSString stringWithFormat:#"RefreshForm()"];
[webview stringByEvaluatingJavaScriptFromString:uploadPhotosCallbackstring];
});
});
}
else {
UIAlertView *ErrorAlert=[[UIAlertView alloc] initWithTitle:#"Error" message:#"Please Upload Photo Above 250x250 size" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[ErrorAlert show];
NSLog(#"conversionImage.size.height %f",conversionImage.size.height);
NSLog(#"conversionImage.size.width %f",conversionImage.size.width);
}
}
-(void)uploadImage
{
NSString *mimetype = #"image/jpeg";
NSString *myimgname = _txt_fname.text; //#"img"; //upload image with this name in server PHP FILE MANAGER
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *imageDataa = UIImagePNGRepresentation(chooseImg.image);
NSDictionary *parameters =#{#"fileimg":defaults }; //#{#"uid": [uidstr valueForKey:#"id"]};
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
//here post url and imagedataa is data conversion of image and fileimg is the upload image with that name in the php code
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:#"POST" URLString:#"http://posturl/newimageupload.php"
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageDataa
name:#"fileimg"
fileName:myimgname
mimeType:mimetype];
}];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestOperation *operation =
[manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success %#", responseObject);
[uploadImgBtn setTitle:#"Uploaded" forState:UIControlStateNormal];
[chooseImg setImage:[UIImage imageNamed:#"invoice-icon.png"]];
if([[responseObject objectForKey:#"status"] rangeOfString:#"Success"].location != NSNotFound)
{
[self alertMsg:#"Alert" :#"Upload sucess"];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure %#", error.description);
[chooseImg setImage:[UIImage imageNamed:#"invoice-icon.png"]];
uploadImgBtn.enabled = YES;
}];
// 4. Set the progress block of the operation.
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
float myprog = (float)totalBytesWritten/totalBytesExpectedToWrite*100;
NSLog(#"Wrote %f ", myprog);
}];
// 5. Begin!
[operation start];
}
Try this this is work for me.
NSData *postData = [Imagedata dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:apiString]];
[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 *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding];
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseDictft = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];

How to do a simple form-urlencoded POST request in AFNetworking 2.0?

How do I replicate this NSURLConnection code in AFNetworking 2.0?
NSString *post = #"key=xxx";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://test.com/"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
Short answer: use the AFHTTPRequestSerializer provided by AFNetworking.
According to the document:
[[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:URLString parameters:parameters];
sends:
POST http://example.com/
Content-Type: application/x-www-form-urlencoded
foo=bar&baz[]=1&baz[]=2&baz[]=3
If you are using AFHTTPRequestOperationManager:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
// you can use different serializer for response.
manager.responseSerializer = [AFJSONResponseSerializer serializer];
It is given in the AFNetworking page github link
The code for sending post request is below, just import the AFNeworking folder in your project in xocde and add necessary frameworks getting started with afnetworking
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"key": #"xxx"};
[manager POST:#"http://test.com" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
In order to POST form-data with AFNetworking you must create this format out of your NSDictionary:
say you have to send these params :
{
key1 = val1;
key2 = val2;
key3 = val3;
}
create this format and encode data using UTF8Encoding :
key1=val1&key2=val2&key3=val3
You can use this formatting :
NSMutableString *str = [[NSMutableString alloc]init];
NSArray *allKeys = [dict allKeys];
for (NSString *key in allKeys) {
[str appendString:key];
[str appendString:#"="];
[str appendString:[dict valueForKey:key]];
[str appendString:#"&"];
}
[str deleteCharactersInRange:NSMakeRange([str length]-1, 1)];
NSData *requestBodyData = [str dataUsingEncoding:NSUTF8StringEncoding];
AFNetworking creates NSMutableRequest. In the HTTPBody of NSMutableRequest instance pass this requestBodyData.
Done.

iOS: handling HTTP request's unicode characters

When I NSLog HTTP requests response string, it appears as "ãÃÂïãÃâ¬ÃÂãÃÂÃâãÃÂ" and something different appears on UILabel but not the same as I expect in Japanese/Chinese format. I am using ASIHTTPRequest and as mentioned here I have set response encoding to NSUTF8StringEncoding(server uses UTF-8 same) but it didn't help. Could someone please tell me how to support unicode character in my App? Thanks.
- (void)getData
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[dataUrl stringByAppendingFormat:#"%#",self.selectedID]]];
[request setResponseEncoding:NSUTF8StringEncoding];
SBJSON *parser = [[SBJSON alloc] init];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithCapacity:3];
[data setObject:self.username forKey:#"username"];
[data setObject:self.password forKey:#"password"];
NSString *dataJSON = [parser stringWithFragment:data error:nil];
[request appendPostData:[dataJSON dataUsingEncoding:NSUTF8StringEncoding]];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestSuccess:)];
[request setDidFailSelector:#selector(requestFailed:)];
[self.queue addOperation: request];
[self.queue go];
}
- (void)requestSuccess:(ASIHTTPRequest *)request
{
NSLog(#"success: %#", [request responseString]);
}
I managed to fix this. Following is the change!
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[dataUrl stringByAppendingFormat:#"%#",self.selectedID]]];
[request setResponseEncoding:NSUTF8StringEncoding]; -- > Wrong!!!
request.defaultResponseEncoding = NSUTF8StringEncoding; --> Correct!

NSMutableURLRequest transform to ASIFormDataRequest

I have writen the fellowing code:
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
postStr = #"user_name=Thomas Tan&phone=01234567891&password=123456";
NSData *myRequestData = [NSData dataWithBytes:[postStr UTF8String] length:[postStr length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: myRequestData];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
it works well,but now I want to use asihttprequest framework,so how to change the above code,I have writen the code,but it can't get the correct result and just get the server error infomation.so what's the problem?
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
NSURL *url = [NSURL URLWithString:urlString];
ASIFormDataRequest *requeset = [ASIFormDataRequest requestWithURL:url];
[requeset setRequestMethod:#"POST"];
[requeset setPostValue:#"Thomas Tan" forKey:#"user_name"];
[requeset setPostValue:#"01234567891" forKey:#"phone"];
[requeset setPostValue:#"123456" forKey:#"password"];
[requeset startSynchronous];
NSError *error = [requeset error];
if (!error) {
NSString *re = [requeset responseString];
NSLog(#"%#",re);
}
NSLog(#"%#",error);
thank you in advance.
UPDATE:
NSString *urlString = [NSString stringWithFormat:ADDRESS,action];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request appendPostData:[#"user_name=Thomas Tan&phone=01234567891&password=123456" dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *re = [request responseString];
NSLog(#"%#",re);
}
NSLog(#"%#",error);
I use the above code ,It also can't get the same result,and error is not nil.
Your ASIHTTP code is not doing the same thing as your NSURLConnection code.
ASIFormDataRequest will automatically:
set the Content-Type header to application/x-www-form-urlencoded
URL-encoded your parameters
That's usually exactly what you want, but if you're getting the correct behavior with your NSURLConnection code and incorrect with ASIHTTP, then you need to change to a custom ASIHTTP POST and use ASIHTTPRequest, not ASIHTTPFormDataRequest, and then manually set the Conten-type back to application/x-www-form-urlencoded:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Content-Type" value:#"application/x-www-form-urlencoded"];
[request appendPostData:[#"user_name=Thomas Tan&phone=01234567891&password=123456" dataUsingEncoding:NSUTF8StringEncoding]];
Doing this, and inspecting exactly what was sent to the server using Wireshark, I can see that the POST data sent is still not quite identical (ASIHTTP on the left, NSURLConnection on the right):
But the content type, length, and actual data is identical.
At this point, I'd expect your server to return the same result.
If it still doesn't, you can edit the ASIhTTP request parameters to match.

ASIHTTPRequest POST to TomCat

When i use ASIHTTPRequest to "POST" to server URI, just response back "null".
URI: "http://www.solok.com:8080/solok_interface/api/web/"
parameter: NSDictionary with key "content".
I try to use ASIHTTPRequest instead of ASIFormDataRequest, but there's no "setPostValue" method.
Any help, thanks!
NSURL * url = [NSURL URLWithString:#"http://localhost:8080/solok_interface/api/web/"];
ASIFormDataRequest *req = [ASIFormDataRequest requestWithURL:url];
[req setRequestMethod:#"POST"];
[req setPostValue:cipherString forKey:#"content"];
[req start];
NSError *error1 = [req error];
if (!error1) {
NSString *reponse = [req responseString];
NSLog(#"Response string is %#",reponse);
}
[req setDelegate:self];
[req setCompletionBlock:^{
NSLog(#"complete");
NSString *responseString = [req responseString];
NSLog(#"the string is %#",responseString);
NSLog(#"The data is %# %d",[req responseStatusMessage],[req responseStatusCode]);
}];
[req setFailedBlock:^{
NSLog(#"#fail");
}];
I didn't use ASIHTTPRequest anymore, the ASI team has stopped to support it. AFNetworking is the right choice for IOS developer.

Resources