本文介绍了在iOS中使用NSURLConnection的表单数据请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在iOS中使用NSURLConnection发布http表单。我在HTML表单中有两个表单字段和一个文件上载选项。当我使用 NSURLConnection 做同样的事情时,我没有收到回复。

I want to make http form post using NSURLConnection in iOS. I have two form fields and one file upload option in an HTML form. When I am doing same thing using NSURLConnection I am not getting a response.

NSString *urlString = @"http://url/test.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data"];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"file\"; filename=\"myphoto.png\"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-streamrnrn"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:filedata];
[body appendData:[[NSString stringWithFormat:@"&s=YL4e6ouKirNDgCk0xV2HKixt&hw=141246514ytdjadh"] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"RETURNED:%@",returnString);

但当我使用并编写以下代码,我正在收到回复。

But when I use ASIHTTPRequest and write the following code it's working and I am getting a response.

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://url/test.php"]];
[request setPostValue:@"YL4e6ouKirNDgCk0xV2HKixt&hw" forKey:@"ssf"];
[request setPostValue:@"141246514ytdjadh" forKey:@"sds"];
[request setData:filedata withFileName:@"myphoto.png" andContentType:@"image/jpeg"  forKey:@"file"];
[request startSynchronous];

NSError *error = [request error];
if (!error) {
    NSString *response = [request responseString];
    NSLog(@"response:%@",response);
}

任何人都可以告诉我我用<$ c $做错了什么c> NSURLConnection part?

Can anyone tell me what I'm doing wrong with the NSURLConnection part?

推荐答案

您没有复制该链接的示例。在该教程中,HTTPBody参数应该是NSData的实例,而不是NSString。

You are not copying the example of that link. In that tutorial, the HTTPBody parameter is supposed to be an instance of NSData, not NSString.

[request setHTTPMethod:@"POST"]; 
NSString *myString = [NSString stringWithFormat:@"value1=test3&value2=test"];
[request setHTTPBody:[myString dataUsingEncoding:NSUTF8StringEncoding]];

这篇关于在iOS中使用NSURLConnection的表单数据请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 13:44