将键/值对添加到NSMutableURLRequest

Don*_*son 2 cocoa-touch ios

虽然有许多相关的问题,但我没有看到一个解决方案,它解决了向NSURLRequest添加多个键/值对的问题.

我想为请求添加一个简单的用户名和密码.我不确定如何添加多对,以及编码.我得到一个有效的连接和响应,但响应表明它无法正确解释请求.

这就是我所拥有的.提前致谢.

NSURL *authenticateURL = [[NSURL alloc] initWithString:@"https://www.the website.com/authenticate"];
NSMutableURLRequest *authenticateRequest = [[NSMutableURLRequest alloc] initWithURL:authenticateURL];
[authenticateRequest setHTTPMethod:@"POST"];
NSString *myRequestString = @"username=";
[myRequestString stringByAppendingString:username];
[myRequestString stringByAppendingString:@"&"];
[myRequestString stringByAppendingString:@"password="];
[myRequestString stringByAppendingString:password];
NSData *requestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[myRequestString length]];
[authenticateRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[authenticateRequest setHTTPBody: requestData];
[authenticateRequest setTimeoutInterval:30.0];

connection = [[NSURLConnection alloc] initWithRequest:authenticateRequest delegate:self]; 
Run Code Online (Sandbox Code Playgroud)

don*_*kim 5

您没有NSString正确使用(myRequestString事实上,您将阅读"username =").相反,试试这个:

NSMutableString *myRequestString = [NSMutableString stringWithString:@"username="];
[myRequestString appendString:username];
[myRequestString appendString:@"&password="];
[myRequestString appendString:password];
Run Code Online (Sandbox Code Playgroud)

除了这个伟大的答案,只是一个典型的示例代码:

-(NSString *)buildKeyValuePostString
    {
    NSString *username = @"boss@apple.com";
    NSString *password = @"macintosh";

    NSMutableString *r = [NSMutableString stringWithString:@""];

    [r appendString:@"command=listFileNames"];
    [r appendString:@"&"];

    [r appendString:@"name=blah"];
    [r appendString:@"&"];

    [r appendString:@"user="];
    [r appendString: [username stringByUrlEncoding] ];
    [r appendString:@"&"];

    [r appendString:@"password="];
    [r appendString: [password stringByUrlEncoding] ];

    return r;
    }
Run Code Online (Sandbox Code Playgroud)

这里是做url编码困难/烦人工作的类别

-(NSString *)stringByUrlEncoding
    {
    return (NSString *)CFBridgingRelease(
             CFURLCreateStringByAddingPercentEscapes(
                NULL,
                (CFStringRef)self,
                NULL,
                (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                kCFStringEncodingUTF8)
                );

    // with thanks to http://www.cocoanetics.com/2009/08/url-encoding/
    // modified for ARC use 2014
    }
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助某人.