我正在尝试使用我正在开发的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];
这是我代表的代码
#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 <>
7 回答
下面的代码描述了一个使用
POST
方法的简单示例 . (如何通过POST
方法传递数据)在这里,我描述了如何使用POST方法 .
1. 使用实际用户名和密码设置发布字符串 .
2. 使用
NSASCIIStringEncoding
对帖子字符串进行编码,以及需要以NSData格式发送的帖子字符串 .您需要发送数据的实际长度 . 计算帖子字符串的长度 .
3. 创建一个Urlrequest,其中包含
HTTP
方法,http Headers 字段等所有属性,其中包含帖子字符串的长度 . 创建URLRequest
对象并初始化它 .设置要将数据发送到该请求的URL .
现在,设置 HTTP 方法(POST或GET) . 在代码中写下这一行 .
设置
HTTP
Headers 字段,其中包含发布数据的长度 .还要为HTTP标头字段设置编码值 .
使用postData设置urlrequest的
HTTPBody
.4. 现在,创建URLConnection对象 . 使用URLRequest初始化它 .
它返回初始化的url连接,并开始加载url请求的数据 . 您可以使用 if/else 语句检查是否正确完成
URL
连接,如下所示 .5. 要从HTTP请求接收数据,可以使用URLConnection类参考提供的委托方法 . 代表方法如下 .
Also Refer This and This documentation for
POST
方法 .以下是源代码为HTTPPost Method.的最佳示例
我不确定为什么,但是一旦我注释掉以下方法,它就会起作用:
此外,我认为您不需要NSUrlConnectionDownloadDelegate协议中的方法,只需要来自NSURLConnectionDataDelegate的方法,除非您需要一些下载信息 .
下面是我在日志库中使用的方法:https://github.com/goktugyil/QorumLogs
此方法填写Google表单中的html表单 . 希望它可以帮助使用Swift的人 .
**使用参数发布API并使用url验证如果json响应键具有状态:“success”
JSON响应:{"status":"success","user_id":"58",_ "user_name":"dilip","result":"You have been logged in successfully"}工作代码
**
在iOS上发送HTTP POST请求(目标c):
Using Swift 3 or 4 you can access these http request for sever communication.
//对于要请求的POST数据
//用于从请求中获取数据
//用于从请求中获取图像或视频等下载内容