問題描述
遠程服務器上的請求總是失敗 (Request always fail on distant server)
I'm using the ASIHTTPRequest for my iOS application. I have to connect to a database through a PHP API (copied below). Here is my function that do the request with ASIHTTPRequest :
-(void)startRequest {
NSURL *url = [NSURL URLWithString:PHP_SCRIPT];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request setStringEncoding:NSUTF8StringEncoding];
[request setTimeOutSeconds:50];
[request setPostValue:@"1" forKey:@"getWines"];
[request startAsynchronous];
}
When I run to an API hosted localy with MAMP all works fine. But when I do it by my distant server, my request always fail, with no message.
Here is my API written in PHP, hosted on my distant server :
<?php
function connectToDB(){
$connexion = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
return $connexion;
}
function getWines($connexion) {
$req = "SELECT name, category FROM table WHERE prize_50 != 0 OR
prize_75 != 0 OR
prize_150 != 0 OR
prize_300 != 0";
$res = mysqli_query($connexion, $req);
echo '[';
while($current = mysqli_fetch_assoc($res)) {
extract($current);
echo json_encode($current);
}
echo ']';
}
function getWine($connexion) {
$name = $_REQUEST["name"];
$req = "SELECT * FROM table WHERE name='".$name."'";
$res = mysqli_query($connexion, $req);
echo "[";
echo json_encode(mysqli_fetch_assoc($res));
echo "]";
}
$connexion = connectToDB();
if($connexion) {
echo "connected";
if(isset($_REQUEST["getWine"])) {
getWine($connexion);
}
else if(isset($_REQUEST["getWines"])) {
getWines($connexion);
}
}
else {
echo "unable to connect to the database";
}
?>
I have no idea what happen, and why it's work on localHost and not on my distant server. If I use the API with a browser like http://myURL/iOS/objc.php?getWines=1 it's work perfectly !
Thank you for helping.
P.S. I have already found a post about make some changes in the code (change the @sythesis for an handwritten getter / setter, but still not working)
參考解法
方法 1:
Your API looks to be expecting a GET request rather than a POST. Create your URL with an NSString containing the entire URL and don't set any POST attributes.
Also, you might want to start checking out a replacement for ASI. It isn't currently being developed and will likely never be ARC compliant. I switched to AFNetworking and love it.