在iOS上发送HTTP POST请求

Daa*_*tik 83 objective-c http-post nsurlconnection ios automatic-ref-counting

我正在尝试使用我正在开发的iOS应用程序发送HTTP Post但是推送从未到达服务器,尽管我确实获得了代码200作为响应(来自urlconnection).我从来没有得到服务器的响应,也没有服务器检测到我的帖子(服务器检测到来自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];
Run Code Online (Sandbox Code Playgroud)

这是我代表的代码

#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
Run Code Online (Sandbox Code Playgroud)

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

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 <>
Run Code Online (Sandbox Code Playgroud)

iPa*_*tel 186

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

在这里,我描述了如何使用POST方法.

1.使用实际用户名和密码设置帖子字符串.

NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"username",@"password"]; 
Run Code Online (Sandbox Code Playgroud)

2.使用NSASCIIStringEncoding以及需要以NSData格式发送的帖子字符串对帖子字符串进行编码.

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
Run Code Online (Sandbox Code Playgroud)

您需要发送数据的实际长度.计算帖子字符串的长度.

NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 
Run Code Online (Sandbox Code Playgroud)

3.创建一个Urlrequest,其中包含所有属性,例如HTTP方法,http标题字段和post字符串的长度.创建URLRequest对象并初始化它.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
Run Code Online (Sandbox Code Playgroud)

设置要将数据发送到该请求的URL.

[request setURL:[NSURL URLWithString:@"http://www.abcde.com/xyz/login.aspx"]]; 
Run Code Online (Sandbox Code Playgroud)

现在,设置HTTP方法(POST或GET).在代码中写下这一行.

[request setHTTPMethod:@"POST"]; 
Run Code Online (Sandbox Code Playgroud)

HTTP使用发布数据的长度设置标题字段.

[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
Run Code Online (Sandbox Code Playgroud)

还要为HTTP标头字段设置编码值.

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
Run Code Online (Sandbox Code Playgroud)

HTTPBody使用postData 设置urlrequest.

[request setHTTPBody:postData];
Run Code Online (Sandbox Code Playgroud)

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

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
Run Code Online (Sandbox Code Playgroud)

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

if(conn) {
    NSLog(@"Connection Successful");
} else {
    NSLog(@"Connection could not be made");
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

有关方法,请参阅 文档 文档POST.

这是HTTPPost方法源代码的最佳示例.