在iOS上发送HTTP POST请求

我试图发送一个HTTP Post与我正在开发的iOS应用程序,但推送永远不会到达服务器,虽然我得到一个代码200作为响应(从URL连接)。 我从来没有得到从服务器的响应也没有检测到我的帖子(服务器检测到来自android的帖子)

我确实使用ARC,但将pd和urlConnection设置为较强。

这是我发送请求的代码

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",dk.baseURL,@"daantest"]]]; [request setHTTPMethod:@"POST"]; [request setValue:@"text/xml" forHTTPHeaderField:@"Content-type"]; NSString *sendString = @"<data><item>Item 1</item><item>Item 2</item></data>"; [request setValue:[NSString stringWithFormat:@"%d", [sendString length]] forHTTPHeaderField:@"Content-length"]; [request setHTTPBody:[sendString dataUsingEncoding:NSUTF8StringEncoding]]; PushDelegate *pushd = [[PushDelegate alloc] init]; pd = pushd; urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:pd]; [urlConnection start]; 

这是我代表的代码

 #import "PushDelegate.h" @implementation PushDelegate @synthesize data; -(id) init { if(self = [super init]) { data = [[NSMutableData alloc]init]; [data setLength:0]; } return self; } - (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten { NSLog(@"didwriteData push"); } - (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes { NSLog(@"connectionDidResumeDownloading push"); } - (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL { NSLog(@"didfinish push @push %@",data); } - (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite { NSLog(@"did send body"); } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [self.data setLength:0]; NSHTTPURLResponse *resp= (NSHTTPURLResponse *) response; NSLog(@"got response with status @push %d",[resp statusCode]); } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d { [self.data appendData:d]; NSLog(@"recieved data @push %@", data); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding]; NSLog(@"didfinishLoading%@",responseText); } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error ", @"") message:[error localizedDescription] delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles:nil] show]; NSLog(@"failed &push"); } // Handle basic authentication challenge if needed - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { NSLog(@"credentials requested"); NSString *username = @"username"; NSString *password = @"password"; NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]; [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; } @end 

控制台始终只打印以下行和以下行:

 2013-04-01 20:35:04.341 ApprenticeXM[3423:907] did send body 2013-04-01 20:35:04.481 ApprenticeXM[3423:907] got response with status @push 200 2013-04-01 20:35:04.484 ApprenticeXM[3423:907] didfinish push @push <> 

下面的代码描述了一个使用POST方法的简单示例( 如何通过POST方法传递数据

在这里,我描述一下如何使用POST方法。

1.用实际的用户名和密码设置后缀字符串。

 NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"username",@"password"]; 

2.使用NSASCIIStringEncoding编码NSASCIIStringEncoding字符串,以及需要以NSData格式发送的NSASCIIStringEncoding字符串。

 NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

你需要发送你的数据的实际长度。 计算后期字符串的长度。

 NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 

3.创建一个Urlrequest,使用所有属性,如HTTP方法,带有后缀字符串长度的http头字段。 创建URLRequest对象并初始化它。

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 

设置您要将数据发送到该请求的Url。

 [request setURL:[NSURL URLWithString:@"http://www.abcde.com/xyz/login.aspx"]]; 

现在,设置HTTP方法( POST或GET )。 把它写在你的代码中。

 [request setHTTPMethod:@"POST"]; 

根据发布数据的长度设置HTTP标题字段。

 [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

同时设置HTTP头字段的编码值。

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

使用HTTPBody设置HTTPBody的HTTPBody。

 [request setHTTPBody:postData]; 

4.现在,创建URLConnection对象。 使用URLRequest初始化它。

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

它返回初始化的url连接,并开始加载url请求的数据。 你可以使用下面的if / else语句来检查你的URL连接是否正确完成。

 if(conn) { NSLog(@"Connection Successful"); } else { NSLog(@"Connection could not be made"); } 

5.要从HTTP请求接收数据,可以使用URLConnection类参考提供的委托方法。 代表方法如下。

 // This method is used to receive the data which we get using post method. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data // This method receives the error report in case of connection is not made to server. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error // This method is used to process the data after connection has made successfully. - (void)connectionDidFinishLoading:(NSURLConnection *)connection 

另请参阅文档POST 文档

这里是HTTPPost方法源代码的最好例子。

我不是很确定为什么,但只要我注释出下面的方法它的工作原理:

 connectionDidFinishDownloading:destinationURL: 

此外,我不认为你需要从NSUrlConnectionDownloadDelegate协议的方法,只有那些从NSURLConnectionDataDelegate,除非你想要一些下载信息。

下面是我在日志库中使用的方法: https : //github.com/goktugyil/QorumLogs

此方法填充了Google表单内的HTML表单。 希望它可以帮助使用Swift的人。

 var url = NSURL(string: urlstring) var request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST" request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding) var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true) 
 -(void)sendingAnHTTPPOSTRequestOniOSWithUserEmailId: (NSString *)emailId withPassword: (NSString *)password{ //Init the NSURLSession with a configuration NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]]; //Create an URLRequest NSURL *url = [NSURL URLWithString:@"http://www.example.com/apis/login_api"]; NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; //Create POST Params and add it to HTTPBody NSString *params = [NSString stringWithFormat:@"email=%@&password=%@",emailId,password]; [urlRequest setHTTPMethod:@"POST"]; [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; //Create task NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { //Handle your response here NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@",responseDict); }]; [dataTask resume]; } 

**发布带有参数的API并使用url进行验证,以便在具有状态的json响应键时导航:“成功”

 NSString *string= [NSString stringWithFormat:@"url?uname=%@&pass=%@&uname_submit=Login",self.txtUsername.text,self.txtPassword.text]; NSLog(@"%@",string); NSURL *url = [NSURL URLWithString:string]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; NSURLResponse *response; NSError *err; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; NSLog(@"responseData: %@", responseData); NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSLog(@"responseData: %@", str); NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil]; NSDictionary* latestLoans = [json objectForKey:@"status"]; NSString *str2=[NSString stringWithFormat:@"%@", latestLoans]; NSString *str3=@"success"; if ([str3 isEqualToString:str2 ]) { [self performSegueWithIdentifier:@"move" sender:nil]; NSLog(@"successfully."); } else { UIAlertController *alert= [UIAlertController alertControllerWithTitle:@"Try Again" message:@"Username or Password is Incorrect." preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){ [self.view endEditing:YES]; } ]; [alert addAction:ok]; [[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]]; [self presentViewController:alert animated:YES completion:nil]; [self.view endEditing:YES]; } 

JSON响应 :{“status”:“success”,“user_id”:“58”,“user_name”:“dilip”,“result”:“您已成功登录”}工作代码

**