我试图将HTTP Post与我正在开发的iOS应用程序一起发送,但推送从未到达服务器,尽管我确实收到了代码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];

这是我的委托代码

#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方法的简单示例.(How one can pass data by 100 method)

在这里,我将介绍如何使用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.创建具有所有属性的URL请求,如HTTP方法,具有POST字符串长度的http报头字段.创建URLRequest对象并对其进行初始化.

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

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

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

现在,设置HTTP方法(POST or GET).按代码中的原样编写此行.

[request setHTTPMethod:@"POST"]; 

使用POST数据的长度设置HTTP标头字段.

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

还要设置HTTP报头字段的编码值.

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

用postData设置urlrequest的HTTPBody.

[request setHTTPBody:postData];

现在,创建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

Also Refer This and This documentation用于POST方法.

下面是源代码为HTTPPost Method.的最佳示例

Ios相关问答推荐

在SwiftUI中使用系统图像和色调创建圆形按钮

与iPadOS中带有扣件的模式相似的组件是什么?

如何在SwiftUI中扩展双击的可检测区域?

如何在SwiftUI中顺时针和逆时针两个方向应用旋转效果?

由于已存在同名项目,因此无法将Mapbox.xcframework-ios.sign复制到Signature中

如何防止UITest套件与Fastlane一起执行?

NSHashTable要求任何MyCustomProtocolAnyObject都是类类型

SwiftUI 点击列表内不会触发 Select

当 .searchable 修饰符处于活动状态时,如何将变量设置为 false?

当 Swift 枚举具有 any existential 作为其关联值之一时,我如何使它符合 `Equatable`?

从 PHAssets 生成图像时,iOS 应用程序因内存问题而崩溃

Swift 共享数据模型在页面之间进行通信.这个怎么运作

在 iOS 8.1 模拟器上更改语言不起作用

aps-environment 始终在发展

'无效更新:第 0 节中的无效行数

如何确定 WKWebView 的内容大小?

在 iOS 上编写文件

如何使用完成按钮制作 UIPickerView?

什么是强属性属性

这是一个什么样的讽刺错误?