如何在iOS中发送异步post请求
我需要一些关于LoginViewController的帮助。 基本上,我有一个小应用程序,我需要发布一些数据到应用程序和即时通讯新的post和JSON。如果我能得到一些帮助和理解,我将不胜感激。下面是我正在处理的一些要求。My.m文件标记为LoginViewController。这就是我目前所拥有的如何在iOS中发送异步post请求,ios,objective-c,json,Ios,Objective C,Json,我需要一些关于LoginViewController的帮助。 基本上,我有一个小应用程序,我需要发布一些数据到应用程序和即时通讯新的post和JSON。如果我能得到一些帮助和理解,我将不胜感激。下面是我正在处理的一些要求。My.m文件标记为LoginViewController。这就是我目前所拥有的 -(void)setRequest { #pragma mark NSURLConnection Delegate Methods - (void)connection:(NSURLConnec
-(void)setRequest {
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
-(void)PostRequest{
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://dev.apppartner.com/AppPartnerProgrammerTest/scripts/login.php"]];
// Specify that it will be a POST request
request.HTTPMethod = @"POST";
// This is how we set header fields
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = @"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
}
我不知道我的设置是否正确。我看到了很多hTTP帖子,但我仍然对如何编写这种语法以及是否需要添加其他内容感到困惑
我需要:
向某个url发送异步POST请求
POST请求必须包含参数“用户名”和“密码”
将收到带有“代码”和“消息”的JSON响应
在UIAlert中显示解析的代码和消息,以及api调用花费的时间(以毫秒为单位)
唯一有效的登录名是用户名:超级密码:qwerty
登录成功后,点击UIAlert上的“OK”将返回MainMenuViewController
我假设方法中的方法是一个打字错误 除非您有特定的理由实现所有这些委托方法,否则您最好使用这两种方法 NSURLSessionDataTask*任务= [[NSURLSession sharedSession]dataTaskWithRequest:请求 completionHandler:^NSData*数据, NSURLResponse*响应, N错误*错误{ //响应完成时要运行的代码。。。 }]; [任务恢复]; 如果您仍然需要支持iOS 6及更早版本和/或OS X v10.8及更早版本,请使用NSURLConnection的sendAsynchronousRequest:queue:completionHandler:方法 但是您缺少的一件大事是请求主体的编码。为此,您可能需要使用URL编码并为此指定适当的MIME类型,如下所示: 基本上,以user=ENCODEDUSERNAME&pass=ENCODEDPASSWORD的形式构建一个字符串接一个字符串,其中两个编码值的构造如下: NSString*encodedString=uuu桥接u传输NSString*CFURLCreateStringByAddingPercentEscapes KCO默认值, __桥接器NSString*原始字符串, 无效的 CFSTR:/?[]@!$&'*+,;=, kCFStringEncodingUTF8;
不要试图通过添加百分比EscapeSusingEncode:和friends来使用StringBy。如果您的字符串包含某些保留的URL字符,它们将做错误的事情。我建议您尝试使用AFNetworking库。 你可以找到代码。
这是一个非常好的教程。你可以这样做
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request addValue:@"YourUsername" forHTTPHeaderField:@"Username"];
[request addValue:@"YourPassword" forHTTPHeaderField:@"Password"];
[NSURLConnection
sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// TODO: Handle/Manage your response ,Data & errors
}];
请不要在标题中大喊大叫。我试图格式化您的代码,但出于某种原因,您似乎在setRequest方法中包含了所有这些方法。为什么?首先,您现在应该使用NSURLSession,而不是NSURLConnection,这在即将发布的iOS 9中已被弃用。其次,这里的内容非常接近,但是如何配置请求的细节完全取决于web服务的编写方式,但是如果您真的发送application/xml请求,我会非常惊讶。application/x-www-form-urlencoded更为常见。或text/json。但是,如果不了解所连接的web服务,我们无法帮助您编写Objective-C代码。这就是客户端代码。嘿,谢谢你的回复。我感到困惑的是,我是ioS新手,所以我只需要正确地放置代码。web服务是JSON。我不应该把xml请求解析部分放进去。但是如果有人能帮我构建这个,我会运行它,看看它是否按照需求编写的方式工作。感谢buchessendAsynchronousRequest在iOS 9中被弃用!使用NSURLSession。[[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^NSData*数据,NSURResponse*响应,NSError*错误{//响应完成后的一段代码。}];这是如何回答这个问题的?
-(IBAction)registerclick:(id)sender
{
if (_password.text==_repassword.text)
{
[_errorlbl setHidden:YES];
NSString *requstUrl=[NSString stringWithFormat:@"http://irtech.com/fresery/index.php?route=api/fresery/registerCustomer"];
NSString *postString=[NSString stringWithFormat:@"name=asd&email=sooraj&phonenumber=8111&password=soorajsnr&type=1&facebookid=&image_path="];
// _name.text,_email.text,_mobile.text,_password.text
NSData *returnData=[[NSData alloc]init];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:requstUrl]];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postString length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
resp=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
c=[[resp valueForKey:@"status" ]objectAtIndex:0];
b=[[resp valueForKey:@"message"]objectAtIndex:0];