创建您的密钥、sha1 或任何您喜欢的算法。确保您的 Web 服务只能通过 https 访问,然后将密钥嵌入到您的请求标头中。是的 ASIHTTPRequest 已贬值,但 AFNetworking 是一个很好的替代品https://github.com/AFNetworking/AFNetworking。在您的 PHP 方面,首先确保您的标头中的 auth 密钥有效,如果是,则进一步验证通过 POST 传递的用户名和密码。这应该可以帮助您,如果您仍然需要帮助,我可以明天发布代码...
更新 - 在下面添加代码
尝试这个...
// setup httpClient
NSURL *baseURL = [NSURL URLWithString:@"https://www.yourWebsite.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
// setup required wsapi parameters
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:username_ forKey:@"username"];
[parameters setObject:password_ forKey:@"password"];
request = [httpClient requestWithMethod:@"POST" path:@"/path/to/your/webservice/authFile.php" parameters:parameters];
// setup request headers
[request setValue:@"68489233957fd9028kd9adf40119c1c93a98c00b80h94lk2jsdo9234720" forHTTPHeaderField:@"wsapiAccessToken"];
// setup request operation blocks
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dictionary = [json_ parseJSONResponse:operation.responseData];
// do something with your response here...
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// handle error
}];
[operation start];
在您的服务器端使用 PHP 使用类似的东西...
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/wsapi/functions/authFunctions.php');
if(accessTokenIsValid())
{
if((isset($_POST['username'])) && (isset($_POST['password'])))
{
// validate passed username and password and do whatever else you need to do.
// be sure to respond back with something so that your app can do something
// useful with the response like give access to the app on success or show
// an error message on failure
}
else
{
$responseArray = array('authResponse'=>'__PARAMSERROR__');
echo json_encode($responseArray);
exit;
}
}
else
{
$responseArray = array('authResponse'=>'__AUTHERROR__');
echo json_encode($responseArray);
exit;
}
?>
请注意,我在这里使用了一个名为的函数accessTokenIsValid
,如下所示。
function getWsapiAccessToken()
{
$tokenString = "Some string here";
// add some salt if you like - make this harder to guess
return sha1($tokenString);
}
function accessTokenIsValid()
{
if( $_SERVER['HTTP_WSAPIACCESSTOKEN'] == getWsapiAccessToken() )
{
return true;
}
else
{
return false;
}
}
希望这可以帮助!