我正在使用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,我错过了什么吗?