将键/值对添加到NSMutableURLRequest

时间:2012-02-05 03:09:08

标签: ios cocoa-touch

虽然有很多相关的问题,但我没有看到一个解决方案,它解决了向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]; 

2 个答案:

答案 0 :(得分:5)

您没有正确使用NSString(您的myRequestString实际上会读取“username =”)。相反,试试这个:

NSMutableString *myRequestString = [NSMutableString stringWithString:@"username="];
[myRequestString appendString:username];
[myRequestString appendString:@"&password="];
[myRequestString appendString:password];

除了这个伟大的答案之外,还有一个典型的示例代码:

-(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;
    }

这里是进行网址编码困难/烦人工作的类别

-(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
    }

希望它有所帮助。

答案 1 :(得分:0)

假设您要将HTTP标头字段添加到请求中,请使用:

-addValue:forHTTPHeaderField: