我想用POST
方法将一个数据发送到一个网址,并从该网址收到回复。
我将此代码编写为发送数据(“ a ”)到此网址(“ http://www.test.com/test/msht ”)
这是我的代码,但没有工作请指导我如何发送数据并从网址给出答案。
-(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 :(得分:1)
我的朋友你的代码错了!!!你应该在帖子NSString中确定帖子值的名称.... 您不能仅发送 a 值。
如果在服务器中获取post方法名称为 user :
,则应编写此代码NSString *post = [NSString stringWithFormat:@"user=a"];