試圖向遠程PHP文件發出簡單的發佈請求。我沒有收到服務器上的參數。我使用Postman Btw收到的。所以這項服務似乎沒問題。有些東西似乎缺少iOS代碼。發佈請求未從iOS設備到達服務器
- (void) sendPostRequest {
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:baseURLPost];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:
@"JSON", @"responseType",
[UserManager sharedInstance].user.username, @"username",
self.textView.text, @"text",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
allowLossyConversion:YES];
[request setHTTPBody:postData];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"%@", [error.userInfo valueForKey:@"NSDebugDescription"]);
} else {
NSArray *jsonResponseArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(@"%@", jsonResponseArray);
}
}] resume];
}
我的PHP代碼來接收post REquest。
<?php
header("Content-type:application/json");
$postText= $_POST['text'];
$username = $_POST['username'];
$itemType = $_POST['itemType'];
$responseType = $_POST['responseType'];
$pictureLink = $_POST['pictureLink'];
$timestamp = $_POST['timestamp'];
$tags = $_POST['tags'];
if($timestamp==null){
$timestamp = date('Y-m-d G:i:s');
}
$arr = array('username' => $username);
echo json_encode($arr);
?>
從這裏jsonResponseArray
是username = "<null>";
感謝您對php代碼的所有幫助。我仍然想保持這個問題幾天,我的PHP代碼是非常古老的,並在過去爲我工作。我希望有人會用我的obj-c來幫助我一些,而且我不會那麼改變我的php代碼。 – CalZone
@BabakT你可以解釋爲什麼這個工程,通過使用$ _POST?我有同樣的問題,使用來自objC應用程序的POST請求將JSON發送到服務器,但我只能使用php:// input fopen調用訪問JSON。我很好奇爲什麼。 – Tiago