2

を扱うアプリを作っています。API

だから私はAPIusingを呼び出そうとしていますcURLが、問題は、APIがアプリを使用するクライアントCookieではなく、このcurl呼び出しを行うサーバーCookieを処理することです...

例: クライアントは既に api にログインしていますが、クライアントが curl 呼び出しでログインしているかどうかを確認すると、許可されていないという api 応答が返されます。

では、どうすればAPIクライアントの Cookie を処理したり、クライアントの Cookie を に渡したりできますAPIか?

4

2 に答える 2

1

次のように、cookiefile を使用する必要があります。

        # Set the cookiefile name, which will allow us to store the cookie and present it later for all requests that require it...
        $cookiefile = tempnam("/tmp", "cookies");
        $agent     = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";

        # Set the user name and password values
        $user      = $argv[1];
        $password      = $argv[2];

        # The API url, to do the login
        $url = "https://some_site.com/login.php?WID=$user&PW=$password";

        # Initialise CURL
        $ch = curl_init();

        # Set all the various options
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_userAGENT, $agent);
        curl_setopt($ch, CURLOPT_POST, 0); // set POST method
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
        curl_setopt($ch, CURLOPT_userPWD, $user.":".$password);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        # Execute the first CURL request to perform the login...
        $results = curl_exec($ch);

        # Setup our next request...
        $job_id_number      = $argv[3];
        $url = "https://some_site.com/request.php?task=add&taskID=$job_id_number";

        # We do not have to initialise CURL again, however we do need to adjust our URL option for the second request...
        curl_setopt($ch, CURLOPT_URL, $url);

        #Remember to use the same cookiefile as above  
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

        # Execute the second CURL call  to perform the action (using the cookie we retrieved from earlier)
        $results = curl_exec($ch);

        echo "$results";
于 2013-03-15T16:59:20.447 に答える
0

API のドキュメントを確認する必要があります。ドキュメントには、クライアントを承認する方法が記載されている可能性があります。

Cookie はサーバーではなくクライアント側 (ブラウザー) で設定されるため、この方法では機能しません。そのため、cURl 呼び出しを行った場合、Cookie データはリクエストに含まれません。Javascript を介した API 呼び出しは、クライアントが (必要な Cookie を使用して) 送信する要求であるため、機能する可能性があります。

于 2013-03-15T17:00:25.530 に答える