gpt4 book ai didi

ios - 在 iOS 上发送 HTTP POST 请求

转载 作者:行者123 更新时间:2023-12-01 16:51:14 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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

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

2. 使用 NSASCIIStringEncoding 对帖子字符串进行编码以及您需要以 NSData 格式发送的帖子字符串。
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 header 字段的编码值。
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

设置 HTTPBody带有 postData 的 urlrequest。
[request setHTTPBody:postData];

4. 现在,创建 URLConnection 对象。使用 URLRequest 对其进行初始化。
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

它返回初始化的 url 连接并开始为 url 请求加载数据。您可以检查您是否 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/15696992/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com