ASIHTTPRequest POST to TomCat - ios

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.

Related

How will I convert this ASIFormDataRequest into AFNetworking?

This is the code Im using for ASIHTTPRequest I want to convert this to AFNetworking
NSURL *url = [NSURL URLWithString:path];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addPostValue:self.theNewJob.jobID forKey:#"form[job_id]"];
[request addPostValue:thisJTF.typeFieldID forKey:#"form[jtf_id]"];
[request setFile:fullPath forKey:#"form[userfile]"];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
if ([response isEqualToString:#"SUCCESS"]) {
// debugger
NSLog(#"signature file uploaded");
} else {
// debugger
NSLog(#"signature file upload Fail: %# response: %#", error, response);
}
}
You need to replace all methods manually. I looked for it and I think below link is good to start: http://door3.com/insights/ios-programming-converting-asihttprequest-afnetworking

ASIFormDataRequest returns NULL when trying to request a POST method

Hi im trying to make a POST request
my code:
NSURL *url = [NSURL URLWithString:urlString];
__weak ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setCompletionBlock:^{
NSString *result = [request responseString];
NSDictionary *dict = [result JSON];
NSLog(#"dict -%#",dict);
}];
[request setFailedBlock:^{
NSLog(#"error %#",[request error]);
}];
[request startAsynchronous];
when I run my code it returns a (null) value. My urlString is correct and the request didn't give me error also. I've tried it on web and returns a {"status":"success"} (it will return a dictionary with status successful or failed).
Use Like this. Hope this will help.
-(void)exe method
{
NSString *strURL=#"---your URL----";
NSURL *url=[NSURL URLWithString:strURL];
ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSError *error;
if(!error)
{
NSString *receivedString = [request responseString];
NSDictionary *dic = [receivedString JSONValue];
NSLog(#"output %#",dic);
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
}
Try with this code -
NSURL *url = [NSURL URLWithString:urlString];
__unsafe_unretained ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setDelegate:self];
__block id jsonData;
[request setTimeOutSeconds:300];
[request setCompletionBlock:^(){
NSError *error = nil;
NSString *responseString = (request.responseString.length)?request.responseString:#"";
NSLog(#"%#",responseString);
NSData *responseData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
jsonData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if(error)
completionBlock(nil, error, task);
else
completionBlock(jsonData, error, task);
}];
[request setFailedBlock:^{
completionBlock(nil, request.error, task);
}];
[request startAsynchronous];
Might be it will helpfull for you.
Did you set your headers in the script that returns JSON correctly? Assuming you're using PHP:
header('Content-Type: application/json');
The default MIME-type is "text/plain", instead of "application/json". If you dont set the MIME-type correctly you're basicly trying to parse the whole document.
So instead of:
{"status":"success"}
You are most likely trying to parse:
<html>
<head></head>
<body>{"status":"success"}</body>
</html>
-(void)exe method
{
NSString *strURL=#"---your URL----";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setTimeOutSeconds:60];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *receivedString = [request responseString];
NSLog(#"output %#",receivedString );
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSString *receivedString = [request responseString];
NSLog(#"output %#",receivedString );
}

data type application/x-www-form-urlencoded from json error

I have a problem:
I need to make a post to a php using json, but it responds only with the data type x-www-form-urlencoded, I used the postman of google chrome and not form-data is done, I used this way but tells me that the parameters are incorrect, I need help:
NSString *jsonRequest = [NSString stringWithFormat:#"j_username=%#&j_password=%#",nombre,pass];
NSURL *url = [NSURL URLWithString:urlhttp];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
[NSURLConnection connectionWithRequest:request delegate:self];
For starters:
Your string has nothing to do with JSON. It's just a plain string
Your username & password must be URL encoded
[NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]] is wrong. You would have to use [NSData dataWithBytes:[jsonRequest UTF8String] length:[[jsonRequest UTF8String] length]]
Where's JSON in your example? You have nothing looking like it in the example.
You're doing a few things wrong in setting up the request, check Sulthan answer.
My advice is to use a library that handles such minor formal details - like encoding and headers - for you.
With AFNetworking you could write something like.
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://whatever.com/"]];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[httpClient setParameterEncoding:AFFormURLParameterEncoding]
NSDictionary * params = #{
#"j_username": nombre,
#"j_password": pass
};
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"relative/path/to/resource"
parameters:params];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[httpClient enqueueHTTPRequestOperation:operation];
(example based on http://samwize.com/2012/10/25/simple-get-post-afnetworking/)
While in terms on LOC in may look not so great, consider that:
httpClient is initialized just once and you can reuse it for subsequent requests, centralizing the configuration
parameters gets automatically encoded in the desired format and if you have to change the encoding in the future you just have to change AFFormURLParameterEncoding to something else.
you get a nice block-based API instead of relying on the cumbersome NSURLConnectionDelegate methods

Issues Getting Receipt Verification Working With ASIHTTPRequest

I am trying to verify a non-renewable subscription with Apple's sandbox server but keep getting back verify response: { "status":21002 } which means the request is malformed. Here is the relevant code I am using:
NSString *receiptString = [[NSString alloc] initWithData:transactionReceipt
encoding:NSUTF8StringEncoding];
NSString *encodedString = [receiptString base64Encoding];
NSString *jsonString = [NSString stringWithFormat:#"{ 'receipt-data' : '%#' }", encodedString];
NSURL *verificationURL = [NSURL URLWithString:#"https://sandbox.itunes.apple.com/verifyReceipt"];
__block ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:verificationURL];
[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
NSLog(#"verify response: %#", responseString);
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(#"verify error: %#", [error description]);
}];
[request startAsynchronous];
Apparently the problem is the way I am sending the data to Apple through the ASIHTTPRequest library. Any insight on this appreciated. Thanks in advance!
Try to use another code. Example,
IAP_Validation

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.

Resources