将键/值对添加到NSMutableURLRequest [英] Add key/value pairs to NSMutableURLRequest
问题描述
虽然有很多相关问题,我没有看到一个解决添加多个键/值对到NSURLRequest。
Although there are many related questions, I don't see one that addresses adding multiple key/value pairs to an NSURLRequest.
我要为请求添加一个简单的用户名和密码。我不确定如何添加多个对,以及编码。我获得有效的连接和响应,但响应表明它无法正确解释请求。
I want to add a simple username and password to a request. I'm unsure of how to add multiple pairs, and also of the encoding. I get a valid connection and response, but the response indicates it hasn't been able to interpret the request properly.
这是我的。提前致谢。
Here's what I've got. Thanks in advance.
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];
推荐答案
NSString 正确(你的 myRequestString
,实际上,会读取username =)。请尝试以下方法:
You're not using NSString
correctly (your myRequestString
, in fact, will read "username="). Instead, try this:
NSMutableString *myRequestString = [NSMutableString stringWithString:@"username="];
[myRequestString appendString:username];
[myRequestString appendString:@"&password="];
[myRequestString appendString:password];
继续这个伟大的答案,只是一个典型的例子代码:
Further to this great answer, just a typical example code:
-(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;
}
这里是做困难/烦人的url编码工作的类别
and here's the category to do the difficult/annoying job of url encoding
-(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
}
希望它能帮助别人。
这篇关于将键/值对添加到NSMutableURLRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!