Отправка данных POST из iPhone по HTTPS SSL

Scrapy походит на потенциальный ответ на мой вопрос. Его домашняя страница описывает мою точную задачу. (Хотя я не уверен, насколько стабильный код все же.)

27
задан shinto Joseph 16 October 2009 в 04:57
поделиться

4 ответа

Вы отправляете запрос как NSASCIIStringEncoding, но ищете NSUTF8StringEncoding

Я бы установил

NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

и

[request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];

, однако, как заметил Николай, это было бы проще, если бы мы знали, что ошибка была: -)

9
ответ дан 28 November 2019 в 05:17
поделиться

Наконец-то я получил способ отправлять данные через защищенное соединение с iPhone:

NSString *post =[[NSString alloc] initWithFormat:@"userName=%@&password=%@",userName.text,password.text];
NSURL *url=[NSURL URLWithString:@"https://localhost:443/SSLLogin/Login.php"];

NSLog(post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

/* when we user https, we need to allow any HTTPS cerificates, so add the one line code,to tell teh NSURLRequest to accept any https certificate, i'm not sure about the security aspects
*/

[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"%@",data);

чтобы избежать предупреждающего сообщения, добавьте


@interface NSURLRequest (DummyInterface)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
@end

Любезность:

  1. ко всему моему стеку через поток друзья и сторонники
  2. http://www.cocoadev.com/index.pl?HTTPFileUpload
  3. http://blog.timac.org/?tag=nsurlrequest
28
ответ дан 28 November 2019 в 05:17
поделиться

Ну, это точно не ответ на ваш вопрос. Но в качестве альтернативы взгляните на этот код. Я успешно использую его для отправки имени пользователя и пароля на сервер.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:loginURL]];

//set HTTP Method
[request setHTTPMethod:@"POST"];

//Implement request_body for send request here username and password set into the body.
NSString *request_body = [NSString stringWithFormat:@"Username=%@&Password=%@",[Username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [Password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//set request body into HTTPBody.
[request setHTTPBody:[request_body dataUsingEncoding:NSUTF8StringEncoding]];

//set request url to the NSURLConnection
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];


if(theConnection) //get the response and retain it

Затем вы можете реализовать следующий делегат для проверки ответа

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

Надеюсь, это поможет.

8
ответ дан 28 November 2019 в 05:17
поделиться

To debug HTTP issues, your best bet is to get the Charles HTTP proxy app - it will record all HTTP communication to and from a server, through the simulator (and you can even set it as a proxy for the phone if you need to).

Then, use the program Curl (from Terminal, it is built in) to generate a working post request (you'll have to search online for examples of using CURL). Then you simply compare how a working request from CURL is formatted, to what your application is sending... note that the simulator is automatically re-directed to work through Charles, you have to tell curl the proxy address to use to have things sent through Charles.

0
ответ дан 28 November 2019 в 05:17
поделиться
Другие вопросы по тегам:

Похожие вопросы: