NSMutableURLRequestおよび特殊文字付きのパスワードは機能しません
-
06-07-2019 - |
質問
Webサービスと通信する小さなプログラムを作成しています(Cocoa Touchを使用)。 Webサービスを呼び出すためのコードは次のとおりです。
- (IBAction)send:(id)sender
{
if ([number.text length] > 0)
{
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
[activityIndicator startAnimating];
NSString *modded;
modded = [self computeNumber];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:@"https://tester:%=&=-Test2009@samurai.sipgate.net/RPC2"]];
[theRequest setHTTPMethod:@"POST"];
[theRequest addValue:@"text/xml" forHTTPHeaderField:@"content-type"];
[theRequest setCachePolicy:NSURLCacheStorageNotAllowed];
[theRequest setTimeoutInterval:5.0];
NSString* pStr = [[NSString alloc] initWithFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>samurai.SessionInitiate</methodName><params><param><value><struct><member><name>LocalUri</name><value><string></string></value></member><member><name>RemoteUri</name><value><string>sip:%@@sipgate.net</string></value></member><member><name>TOS</name><value><string>text</string></value></member><member><name>Content</name><value><string>%@</string></value></member><member><name>Schedule</name><value><string></string></value></member></struct></value></param></params></methodCall>", modded, TextView.text];
NSData* pBody = [pStr dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:pBody];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (!theConnection)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"A Connection could not be established!"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
sendButton.enabled = TRUE;
return;
}
[pStr release];
[pBody release];
}
}
ユーザー名とパスワードはURLに含まれている必要があり、ほとんどの場合で機能しますが、パスワードが例の&quot;%=&amp; =-Test2009&quot;のような特殊文字で構成されている場合、Webサービスは応答しません。 「Test2009」のようなものの場合正常に動作します。誰かがその理由を知っており、おそらくそれに対する解決策がありますか?
解決
特殊文字は、エンコードされたURL、要求したURLである必要があります。
https://tester:%=&=-Test2009@samurai.sipgate.net/RPC2
..は無効です。具体的には、%=
部分(%
は文字のエスケープに使用されます。たとえば、%20
はスペース)、そう..
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:@"https://tester:%=&=-Test2009@samurai.sipgate.net/RPC2"]];
..のように変更する必要があります:
NSString *theAddress = [NSString stringWithFormat:@"https://%@:%@@%@",
[@"tester" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[@"%=&=-Test2009" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
@"example.com"];
NSURL *theURL = [NSURL URLWithString:theAddress];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL];
これはURL https:// tester:%25 =&amp; =-Test2009@example.com
他のヒント
URLを作成するときは、文字列にURLセーフ文字を使用する必要があります。このNSStringメソッドを使用してください stringByAddingPercentEscapesUsingEncoding:これはあなたのためにこれを行います。
所属していません StackOverflow