2014-09-04 9 views
1

Я хочу отправить одну информацию с помощью метода POST на один URL-адрес и получить ответ с этого URL-адреса. я пишу этот код для отправки данных («„) на этот адрес (“http://www.test.com/test/msht»)как отправить данные на URL с методом POST в Xcode

это мой код, но не работает, пожалуйста, руководство меня, как отправить данные и дать ответ из URL.

-(IBAction)btn_post_clicked:(id)sender{ 

    //if there is a connection going on just cancel it. 
    [self.connection cancel]; 

    //initialize new mutable data 
    NSMutableData *data = [[NSMutableData alloc] init]; 
    self.receivedData = data; 
    [data release]; 

    //initialize url that is going to be fetched. 
    NSURL *url = [NSURL URLWithString:@"http://www.test.com/test/msht"]; 

    //initialize a request from url 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]]; 

    //set http method 
    [request setHTTPMethod:@"POST"]; 
    //initialize a post data 
    NSString *postData = [[NSString alloc] initWithString:@"a"]; 
    //set request content type we MUST set this value. 

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

    //set post data of request 
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]]; 
    //initialize a connection from request 
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    self.connection = connection; 
    [connection release]; 

    //start the connection 
    [connection start]; 


} 
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ 
    [self.receivedData appendData:data]; 
} 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ 

    NSLog(@"%@" , error); 
} 

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

    //initialize convert the received data to string with UTF8 encoding 
    NSString *htmlSTR = [[NSString alloc] initWithData:self.receivedData 
               encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@" , htmlSTR); 
} 

ответ

0

Друг ваш код неверен !!! вы должны определить имя значения post в пост NSString .... Вы не отправляете a значение.

вы должны написать этот код, если имя прибудет после метода в сервере пользователя:

NSString *post = [NSString stringWithFormat:@"user=a"]; 
Смежные вопросы