gpt4 book ai didi

ios - 将键/值对添加到 NSMutableURLRequest

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:33:05 25 4
gpt4 key购买 nike

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

最佳答案

你没有正确使用 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;
}

这是完成 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
}

希望对大家有帮助。

关于ios - 将键/值对添加到 NSMutableURLRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9146609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com