(1)IOS客户端Post请求+PHP服务器Post响应
PHP服务器代码:
<?php
if($_POST) {
foreach($_POST as $index => $value) echo "$_POST[$index] = $value", "<BR>";
foreach($_GET as $index => $value) echo "$index = $value", "<BR>";
}
?>
IOS客户端代码:
NSString *urlAsString = @"http://localhost/testPost.php?id=1&password=abc";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:@"POST"];
NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2";
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error) {
if ([data length] >0 && error == nil){
NSString *html =
[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@", html);
}
}输出结果:
HTML = BodyValue1 = BodyValue1<BR>
BodyValue2 = BodyValue2<BR>
id = 1<BR>
password = abc<BR>
注意这里在发送Post请求的时候。并不是所有的数据都放在Post中,还有一部分是以Get的形式发送的,所以这里既打印出了Post的内容,也打印出了Get的内容。(2)IOS客户端Post请求(Json)+PHP服务器Post响应(Json编解码)
PHP服务器代码:
<?php
if($_POST) {
$dataJson = file_get_contents("php://input");
$dataContent = json_decode($dataJson, TRUE);
if($dataContent["id"] == "abc" && $dataContent["password"] == "123"){
$marray = array();
$marray["name"] = "apple";
$marray["price"] = "15.8";
$mJsonContent = json_encode($marray);
echo "$mJsonContent";
}
}
?>
IOS客户端代码:
NSString *urlAsString = @"http://localhost/testPostJSONReturn.php";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSMutableDictionary * tempDic = [NSMutableDictionary dictionary];
[tempDic setValue:@"abc" forKey:@"id"];
[tempDic setValue:@"123" forKey:@"password"];
NSData *postBody = [NSJSONSerialization dataWithJSONObject:tempDic options:NSJSONWritingPrettyPrinted error:nil];
[urlRequest setHTTPBody:postBody];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error) {
if ([data length] >0 && error == nil){
id dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if([dic isKindOfClass:[NSArray class]]){
NSLog(@"array");
}else if([dic isKindOfClass:[NSDictionary class]]){
NSLog(@"dic");
NSDictionary *mdic = (NSDictionary*)dic;
NSString *item = @"";
for (item in mdic.allKeys) {
NSLog(@"%@=%@",item,[mdic valueForKey:item]);
}
}
}
}];
dic
name=apple
price=15.8