繁体   English   中英

在目标C中转换PHP发布请求格式

[英]Converting PHP post request format in objective C

我正在尝试调用用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代码可以很好地工作,但是当我尝试从目标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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM