iOS与php进行简单的post交互

4 篇文章 0 订阅

最近研究了一下这方面的知识,现在贴出代码做一个总结


首先是iOS端的


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    mydata = [[NSMutableData alloc]initWithCapacity:0];
    
	NSURL *url = [NSURL URLWithString:@"http://localhost/test/postDemo.php"];
    
    //创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    
    [request setHTTPMethod:@"POST"];
    
    NSNumber *s = [NSNumber numberWithInt:22];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:[@"com.xinmei365.font" stringByEncodingURIComponent],@"package",s,@"version",@"11",@"channel",@"22",@"type",@"zh",@"lang", nil];
    
    NSString *param = [dict JSONString];
   
    NSData *data = [param dataUsingEncoding:NSUTF8StringEncoding];
    
    //加入json参数
    [request setHTTPBody:data];
    
    NSURLConnection *contect = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//    [contect start];
    
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    mydata.length = 0;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  {
    [mydata appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSString *str = [[NSString alloc]initWithData:mydata encoding:NSUTF8StringEncoding];
    NSDictionary *dict = [str objectFromJSONString];
    NSLog(@"%@",dict);
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"error");
}

下面是php,相当于传上去,再传回来

<?php
	 
	if (!empty($GLOBALS['HTTP_RAW_POST_DATA']))
    {
        $command =  isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        $j = json_decode($command,TRUE);//true,转化成数组
    }
    
    echo json_encode($j);


注意:先设置php.ini中的always_populate_raw_post_data值设为On,这样表示可以接受data数据(这个php.ini是隐藏在etc目录下的,一般的搜索可能也许也搜索不到,需要自己用终端搞定这个问题,如果没有设置的话,可以参考下面的代码)


if (!empty($GLOBALS['HTTP_RAW_POST_DATA']))
    {
        $command =  isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
        $j = json_decode($command,TRUE);
        echo json_encode($j);
    }else if(file_get_contents("php://input")){
        $command = file_get_contents("php://input");
        $j = json_decode($command,TRUE);
        echo json_encode($j);
    }else{
        echo json_encode("error!!!!!!!!!");
    }





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值