0

我正在使用NSMutableURLRequest将一些数据发布到受密码保护的 Web 服务器。我已经连接了一切,我可以很好地检索数据,但由于某种原因,我无法发布任何数据。

我用NSURLCredentials的是用户名和密码,连接没问题。

起始 URL 请求:

-(void)starting {
NSURL *url = [NSURL
URLWithString:@"http:myurl/myfile.txt"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; //Calling NSURLConnection delegate methods
}

转换NSString我想发布到NSData

NSString *someString = @"Hello World";
NSData* theData=[someString dataUsingEncoding:NSUTF8StringEncoding];

NSURL *someUrl = [NSURL URLWithString:@"http://myurl/myfile.txt"]; 

写入网络服务器:

NSString *postLength = [NSString stringWithFormat:@"%d", [theData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:someUrl];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];    
[request setHTTPBody:theData];

允许任何 https 证书:

[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[someUrl host]];

发送检索请求:

NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

检索数据的长度是否 = 0..

if ([data length] == 0) {

    UIAlertView *dataLengthNoneAlert = [[UIAlertView alloc] initWithTitle:@"No data" message:@"There is no data on the server" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil];

    [dataLengthNoneAlert show];

}

如果没有,请告诉我新数据..(应该是“Hello World”)

else {

    NSLog(data);

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Retrieved data" message:data delegate:nil cancelButtonTitle:@"Dimiss" otherButtonTitles:nil, nil];

    [alert show];

}

因此,我“尝试”将数据发布到 Web 服务器,然后立即检索它。我发现我刚才写的数据的长度是 0。我什至检查了应用程序之外的服务器,没有任何变化。网址有效。这是我第一次使用 NSMutableURLRequest,我错过了什么吗?

4

2 回答 2

1

不是一个完整的专家,但有几件事对我有用。

将您的响应存储为类型可能会更好,NSMutableData而不是NSData因为这允许连续的动态响应

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsurlconnection_Class/Reference/Reference.html

^ 的苹果文档还NSUrlconnection建议使用 4 种方法,didRecieveResponse, didRecieveData, didFailwithError这些方法didFinishLoading有助于附加和解释数据。

希望这可以帮助。

于 2012-07-12T15:22:26.043 回答
0

验证您的url 字符串是否以斜杠结尾:

这项工作:

http://your.url/

不起作用

http://your.url
于 2012-09-26T11:24:44.853 回答