最近研究了一下这方面的知识,现在贴出代码做一个总结
首先是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!!!!!!!!!");
}