2013-11-22 6 views
1

안녕 얘들 아 : D 전에서 request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding]; that my program work correctly?POST 요청

이 내 코드

#import "MainClass.h" 

@implementation MainClass 

- (IBAction)actionButton:(id)sender { 

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL 
                    URLWithString:@"https://login.dnevnik.ru"] 
                 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0]; 


request.HTTPMethod = @"POST"; 
NSString *username = _loginLogin.text; 
NSString *password= _passwordLogin.text; 
GlobalUserName = username; 
GlobalPassword = password; 
NSDictionary *param = @{@"Username": GlobalUserName,@"password": GlobalPassword}; 



/*NSUserDefaults *loginData = [NSUserDefaults standardUserDefaults]; 
NSString *username1 = [loginData objectForKey:@"username"] ; 
NSString *password1 = [loginData objectForKey:@"password"];*/ 


//Параметры посылаемого запроса 
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding]; 
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" 
forHTTPHeaderField:@"Content-Type"]; 


NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 


if (connection) { 
    _otvet.text = @"Соединение установлено"; 
    NSLog(@"ama ama"); 

} 
else 
{ 
    [email protected]"Проблема с соединением"; 
    NSLog(@"ama ama faza"); 
} 

} 

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse 
*)response  
{ 
[receivedData setLength:0]; 

} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 

[receivedData appendData:data]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
UIAlertView *errorAlert = [[UIAlertView alloc] 
          initWithTitle:@"Ошибка" message:@"Пожалуйста, проверьте 
соединение с Интернетом." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
[errorAlert show];   
} 


- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 

NSString * data = [[NSString alloc] initWithData:receivedData  
encoding:NSUTF8StringEncoding]; 

if ([data isEqualToString: @"OK"]) { 

    _otvet.text = @"Вы успешно залогинены."; 
    NSLog(@"Вы успешно залогинены."); 
} 
else 
{ 
    NSLog(@"Ошибка авторизации %@,%@",GlobalUserName,GlobalPassword); 
} 
} 

말을해야 180cm 정도 I (이 page에) 클래스는 NSDictionary에서 사용하는 방법을 나에게 설명해주십시오 내 컴파일시 case xcode라고 말합니다.

No visible @interface for 'NSDictionary' declares the selector 'dataUsingEncoding:'

+1

나는이 알고 :

이 작업을 수행 늙은. 그러나 잘하면 응답 할 수 있습니다. 당신은 Mainclass.h에서와 같이 GlobalUserName과 GlobalPassword를 정의 했습니까? – paintball247

답변

2

NSString을 BODY로 전달해야합니다.

NSString *postString = [NSString stringWithFormat:@"Username=%@&password=%@",username,password]; 
request.HTTPBody = [postString dataUsingEncoding:NSUTF8StringEncoding]; 

을 아니면 JSON 문자열에있는 NSDictionary를 인코딩 및 백엔드를 해독하려면 - 그렇게하기 위해 더 좋은 방법,하지만 더 많은 일 :

request.HTTPBody = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&error] 
+0

Super 핸디 답변 감사합니다! – Fattie

+0

다음과 같이해야합니다 .. nsdictionary를 전달할 수 없습니까? NSDictionary는 PHP 스크립트에 전달하는 문제가 있기 때문에 ... NSString은 작동하지만 NSDictionary는 사용할 수 없습니다. – jsetting32

+0

다음과 같이하면됩니다. request.HTTPBody = [NSJSONSerialization dataWithJSONObject : 사전 옵션 : NSJSONWritingPrettyPrinted 오류 : nil] –