雖然有很多相關的問題,但我沒有看到一個將多個鍵/值對添加到NSURLRequest的地址。將鍵/值對添加到NSMutableURLRequest
我想爲請求添加一個簡單的用戶名和密碼。我不確定如何添加多個對以及編碼。我得到了有效的連接和響應,但響應表明它無法正確解釋請求。
這是我得到的。提前致謝。
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];
OK - 謝謝。但即使修復後我的請求仍然沒有正確解釋。用戶名和密碼的設置是否正確完成並編碼? – 2012-02-05 03:24:29
嗯,除了'NSMutableString'部分,其餘的代碼看起來應該像你期望的那樣運行。我的代碼非常類似於您所寫的工作正常。 – donkim 2012-02-05 03:33:11
NSString * myRequestString = @「h = 123」; NSData * myRequestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[myRequestString length]];我們可以使用NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@「http:// localhost:8082/45」]]; [請求setHTTPMethod:@「POST」]; [request setHTTPBody:myRequestData]; [request setValue:@「application/x-www-form-urlencoded」forHTTPHeaderField:@「content-type」]; [[NSURLConnection alloc] initWithRequest:request delegate:self]; – donkim 2012-02-05 03:34:02