在iOS中使用NSURLConnection的表单数据请求

前端之家收集整理的这篇文章主要介绍了在iOS中使用NSURLConnection的表单数据请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在iOS中使用NSURLConnection制作http表单帖子.我在 HTML表单中有两个表单字段和一个文件上载选项.当我使用NSURLConnection做同样的事情时,我没有得到回应.
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);

但是,当我使用ASIHTTPRequest并编写以下代码时,它正在工作,我正在收到回复.

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

任何人都可以告诉我NSURLConnection部分我做错了什么?

解决方法

您没有复制该链接的示例.在该教程中,HTTPBody参数应该是NSData的实例,而不是NSString.
[request setHTTPMethod:@"POST"]; 
NSString *myString = [NSString stringWithFormat:@"value1=test3&value2=test"];
[request setHTTPBody:[myString dataUsingEncoding:NSUTF8StringEncoding]];
原文链接:https://www.f2er.com/iOS/332945.html

猜你在找的iOS相关文章