ios - 在 iOS 上发送 HTTP POST 请求

标签 ios objective-c automatic-ref-counting http-post nsurlconnection

我正在尝试使用我正在开发的 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];

这是我的委托(delegate)代码

#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 对 post 字符串以及您需要以 NSData 格式发送的 post 字符串进行编码。

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

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

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

3. 创建一个带有所有属性的 Urlrequest,例如 HTTP 方法、带有 post 字符串长度的 http header 字段。创建 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 头域为post 数据的长度。

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

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

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

用postData设置urlrequest的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 类引用提供的委托(delegate)方法。 委托(delegate)方法如下。

// 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

另请参阅 This This POST 方法的文档

这是最好的例子,源代码为 HTTPPost Method.

关于ios - 在 iOS 上发送 HTTP POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15749486/

相关文章:

ios - 企业 iOS 应用程序启动缓慢

objective-c - #import 如何在 Objective-C 中搜索文件

objective-c - 为什么我不需要 CFRetain() 这段代码中 ABAddressBookGetPersonWithRecordID() 的结果

ios - 在 Xcode 10.2 中使用 Swift 3 - Command/Library/Developer/Toolchains/swift-3.0-RELEASE.xctoolchain/usr/bin/swiftc 失败,退出代码为 1

ios - XCUIApplication 上的 swipeUp() 破坏了 UITest 中的 XCUIApplication

ios - 添加本地化时的 Xcode 未找到所有 Storyboard

objective-c - NSButton 在 NSImageView 上显示时出现渲染问题

iphone - CGBitmapContextCreate 的内存使用率非常高

ios - 为什么直接将对象分配给属性时 ARC 无法正常工作

objective-c - 为什么基于文档的应用程序 IBActions 内的 IBOutlet 为零?