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"];
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];
}
そうでない場合は、新しいデータを教えてください。(「HelloWorld」である必要があります)
else {
NSLog(data);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Retrieved data" message:data delegate:nil cancelButtonTitle:@"Dimiss" otherButtonTitles:nil, nil];
[alert show];
}
そのため、データをWebサーバーに投稿し、その直後にデータを取得しようとしています。書いたと思われるデータの長さが0であることがわかりました。アプリケーションの外部でサーバーをチェックしても、何も変わりません。URLは有効です。NSMutableURLRequestを使用するのはこれが初めてですが、何かが足りませんか?