我使用NSMutableURLRequest
發佈一些數據密碼保護的Web服務器。我已經連接好了,並且可以檢索數據,但由於某種原因,我無法發佈任何內容。問題發佈數據到網絡服務器與NSMutableURLRequest
我使用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"];
寫入到Web服務器:
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,我錯過了什麼?
''的方法NSURLConnection's' sendSynchronousRequest:returningResponse:error:'在解釋服務器數據時工作正常。問題發佈到它。 – Imirak 2012-07-12 15:37:25
嘗試'NSData * theData = [NSData dataWithBytes:[someString UTF8String] length:[someString length]];'和'NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:someURL]; – 2012-07-12 15:50:54
該請求包含在開始認證(我沒有在問題中提到)和'NSData * theData = [NSData dataWithBytes:[someString UTF8String] length:[someString length]];'沒有改變任何東西。但也許編碼類型與它有關... – Imirak 2012-07-12 16:08:59