我正在使用NSMutableURLRequest
将一些数据发布到受密码保护的Web服务器上。我已经连接了所有东西,我可以很好地检索数据,但由于某种原因我无法发布任何内容。
我使用NSURLCredentials
作为用户名和密码,连接没问题。
启动网址请求:
-(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,我错过了什么吗?
答案 0 :(得分:1)
不是一个完整的专家,但有几件事要尝试对我有用。
将响应存储为NSMutableData
类型而不是NSData
可能更好,因为这样可以实现持续的动态响应
另外,NSUrlconnection
^的苹果文档建议使用4种方法,didRecieveResponse, didRecieveData, didFailwithError
和didFinishLoading
,这有助于追加和解释数据。
希望这会有所帮助。
答案 1 :(得分:0)
验证您的网址字符串是否以斜杠结尾:
这项工作:
http://your.url/
不有效:
http://your.url