我需要使用post方法将用户名和密码传递给url。我也希望从service.can获得响应。任何人都请告诉有效的方法吗?
答案 0 :(得分:1)
data not post through webservice json in ios
查看此链接,了解我就您的问题提出的问题所发布的答案。希望它会对你有所帮助。
答案 1 :(得分:1)
在.h文件中添加此代码
@interface xyz
@property (retain, nonatomic) NSMutableData *receivedData;
@property (retain, nonatomic) NSURLConnection *connection;
在.m文件中添加此代码 @implementation ........
@synthesize receivedData,connection;
-(void)requesttoserver
{
//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;
//initialize url that is going to be fetched.
NSURL *url = [NSURL URLWithString:@"https://www.your urlname"];
//initialize a request from url
request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
//set http method
[request setHTTPMethod:@"POST"];
//initialize a post data
NSString *postData = @"username password";
//set request content type we MUST set this value.
[request setValue:@"application/x-www-form-urlencoded;" forHTTPHeaderField:@"Content-Type" ];
//set post data of request
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
//initialize a connection from request
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%@" , error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *htmlSTR = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
}
要发布数据时调用requesttoserver
方法
答案 2 :(得分:1)
我试过这个
NSString *Post=[NSString stringWithFormat:@"email=%@&password=%@&password_confirmation=%@",[textfieldArray objectAtIndex:0],[textfieldArray objectAtIndex:1],[textfieldArray objectAtIndex:2]];
NSData *PostData = [Post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *PostLengh=[NSString stringWithFormat:@"%d",[Post length]];
NSURL *Url=[NSURL URLWithString: @"http://offers2win.com/api/v1/users/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:Url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:PostLengh forHTTPHeaderField:@"Content-Lenght"];
[request setHTTPBody:PostData];
NSData *ReturnData =[NSURLConnection sendSynchronousRequest:request returningResponse:Nil error:Nil];
NSString *Response = [[NSString alloc] initWithData:ReturnData encoding:NSUTF8StringEncoding];
//Response = [Response stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"Response%@",Response);