1

我已经编写了同伴代码:

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

它运行良好,但现在我想使用 asihttprequest 框架,那么如何更改上面的代码,我已经编写了代码,但它无法得到正确的结果,只是得到服务器错误信息。所以有什么问题?

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

先感谢您。

更新:

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

我使用上面的代码,它也不能得到相同的结果,并且错误不是零。

4

1 回答 1

0

您的 ASIHTTP 代码与您的 NSURLConnection 代码做的事情不同。ASIFormDataRequest 将自动:

这通常正是您想要的,但是如果您的 NSURLConnection 代码的行为正确,而 ASIHTTP 的行为不正确,那么您需要更改为自定义 ASIHTTP POST并使用 ASIHTTPRequest,而不是 ASIHTTPFormDataRequest,然后手动设置 Conten-type回到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]];

这样做,并使用Wireshark检查发送到服务器的确切内容,我可以看到发送的 POST 数据仍然不太相同(左侧为 ASIHTTP,右侧为 NSURLConnection):

后差异

但内容类型、长度和实际数据是相同的。此时,我希望您的服务器返回相同的结果。如果仍然没有,您可以编辑 ASIhTTP 请求参数以进行匹配。

于 2012-05-06T06:09:34.533 回答