gpt4 book ai didi

php - 在 Objective-C 中转换 PHP post 请求格式

转载 作者:行者123 更新时间:2023-11-29 10:59:09 25 4
gpt4 key购买 nike

我正在尝试调用在 PHP 中创建的 Web 服务。当我从 PHP 发送时,请求和响应成功:

    $.post( 
'http://166.178.11.18/server/xs/reliable.php',
{"name":value2}, // any data you want to send to the script
function( data ){
$( 'body ').append( data );

});

这通过 php 代码工作得很好,但是当我试图从 Objective-C 代码发送它时,服务器无法接收参数,响应显示空值请求。我称它为:

   NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:@"POST"];
[theRequest setValue:currentUniqueID forKey:@"name"];

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Do something here
}

但是这个返回空 ID 值的响应。

最佳答案

你可以这样做,

     NSString *post =[[NSString alloc] initWithFormat:@"name=%@",currentUniqueID];

NSLog(@"post ==> %@", post);

NSURL *url=[NSURL URLWithString:@"http://166.178.11.18/server/xs/reliable.php"];

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

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

//NSLog(@" route id is :%@",postLength);

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];


NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"Response ==> %@", responseData);
} else {
if (error) NSLog(@"Error: %@", error);
}

如果 currentUniqueID 是整数,那么 @"name=%@" 将是 @"name=%i"

关于php - 在 Objective-C 中转换 PHP post 请求格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16830443/

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