0

我有这样的格式网址:

NSString *url1 = [NSString stringWithFormat:@"%@",http:abc.com/check?para1= 1,2,3,4,5,6,7,8...,1000&Param2= 1,2,3 ...,1000&Param3=12:12:12.000&Param4=1.12310&Param5=http:yahoo.com/adsf.html]

我在用着

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url1]];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%d", [url1 length]] forHTTPHeaderField:@"Content-length"];
    [request setValue:@"text/plain" forHTTPHeaderField:@"Content-type"];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"response - %@",responseString);

但我无法发送到服务器。

4

2 回答 2

1

我修改了你的代码,请试试这个:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *url1       = [NSString stringWithFormat:@"%@", @"para1= 1,2,3,4,5,6,7,8...,1000&Param2= 1,2,3...,1000&Param3=12:12:12.000&Param4=1.12310&Param5=http:yahoo.com/adsf.html"];
NSData *postData     = [url1 dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];    
NSString *postLength = [NSString stringWithFormat:@"%u", [postData length]];
[request setURL:[NSURL URLWithString:@"http:abc.com/check"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"Close" forHTTPHeaderField:@"Connection"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"text/plain" forHTTPHeaderField:@"Content-type"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];    
NSData *returnData       = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"response - %@",responseString);

愿它能帮助你。

于 2013-06-16T11:26:31.633 回答
0

我怀疑您做错了,并尝试将 POST 正文放入 URL。

我从您尝试根据 url 长度设置内容长度的方式推断出这一点。

帖子正文需要是内容request.HTTPBody = dataToPost

网址不能那么长。


我建议阅读 GET 和 POST 之间的区别

请参阅此问题以查看如何发布数据

如何使用 POST 从 iOS 应用程序发送 NSData?

于 2013-06-16T10:00:20.140 回答