【问题标题】:How to easily send a POST request and receive + interpret JSON using PHP如何使用 PHP 轻松发送 POST 请求并接收 + 解释 JSON
【发布时间】:2012-07-31 23:25:49
【问题描述】:

我正在使用 Foursquare API,我需要向他们的服务器发出请求,以便接收 JSON 格式的访问令牌 (https://developer.foursquare.com/overview/auth)。如何使用 PHP 做到这一点?

我没有在网上找到任何权威的教程,这就是我在这里问的原因。我已经看到了一些我不太了解的与 cURL 相关的东西,那么有什么简单的方法可以做到这一点吗?我在使用 AJAX 之前已经完成了它,它非常不言自明,但它在 PHP 中似乎非常复杂,远远超过它的外观:(

有人可以帮忙吗?谢谢

【问题讨论】:

  • 您需要发送任何特殊的标头吗?还是一个简单的发布请求?
  • 据我所知,这只是一个简单的发布请求,没什么特别的。谢谢:)

标签: php json api post request


【解决方案1】:

好吧,按照您提供的链接,试试这个:

重定向链接中的脚本(YOUR_REGISTERED_REDIRECT_URI)

if(isset($_GET['code']))
{
    $code = $_GET['code'];
    $url = "https://foursquare.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=$code";

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_POST);

    $json = curl_exec($ch);

    var_dump($json);
}

注意:阅读您提供的教程后,我没有看到任何对 POST 请求的引用,只有请求,所以您可以试试这个(而不是 cURL)

$json = file_get_contents($url);

如果是简单的 GET 请求,那么 file_get_contents 可能会起作用。

【讨论】:

  • 非常感谢您的回复,这正是我正在寻找的东西 :) 你介意指导我了解 curl 的具体情况吗?谢谢
  • $json = file_get_contents($url);看起来很不错,但既然我正在发送我的私钥,它不需要是 POST 吗?
  • 嗯,我想是的。这个 API 似乎只需要一个 GET 请求,PHP 自己负责。我相信,CODE 可以作为第一个摇动令牌。响应应该是一个有效的 json 或类似的东西。
【解决方案2】:
<?php

# url_get_contents function by Andy Langton: http://andylangton.co.uk/

function url_get_contents($url,$useragent='cURL',$headers=false,$follow_redirects=false,$debug=false) {

# initialise the CURL library
$ch = curl_init();

# specify the URL to be retrieved
curl_setopt($ch, CURLOPT_URL,$url);

# we want to get the contents of the URL and store it in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

# specify the useragent: this is a required courtesy to site owners
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

# ignore SSL errors
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

# return headers as requested
if ($headers==true){
curl_setopt($ch, CURLOPT_HEADER,1);
}

# only return headers
if ($headers=='headers only') {
curl_setopt($ch, CURLOPT_NOBODY ,1);
}

# follow redirects - note this is disabled by default in most PHP installs from 4.4.4 up
if ($follow_redirects==true) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
}

# if debugging, return an array with CURL's debug info and the URL contents
if ($debug==true) {
$result['contents']=curl_exec($ch);
$result['info']=curl_getinfo($ch);
}

# otherwise just return the contents as a variable
else $result=curl_exec($ch);

# free resources
curl_close($ch);

# send back the data
return $result;
}

?>

【讨论】:

    猜你喜欢
    • 2014-07-13
    • 2011-03-03
    • 2021-01-10
    • 2017-05-31
    • 2011-08-04
    • 2019-02-06
    相关资源
    最近更新 更多