使用PHP获取Webservice数据



请原谅,如果我不能很好地解释,我只是需要一些例子,链接或任何你可以提供给我学习这是如何工作的。

我试图使这个web服务与PHP工作,我也有这个作为一个例子,与JS工作,但这个web服务有一些限制,像"我不能消费至少有不同的原始语言消费者"。

就是这个例子。

$.ajax(
   {
       type:"POST",
       contentType:"application/json;charset=utf-8",
       url:"https://somewebsite.com/setsomedata",
       data:"{}",
       dataType:"json",
       async: false,
       success: function(msg) {
          a("#compInter",msg.d.data1); 
          a("#ventInter",msg.d.data2);
          a("#compAgencia",msg.d.data3);
          a("#ventAgencia",msg.d.data4);
      },
      error: function(textStatus, errorThrown, errorDetail){
          alert(errorDetail);
      }
   });

所以,问题是我不能使用Jquery/Javascript来消费这些数据,因为我需要使用PHP来完成这项工作。

所以,我想我真的在这种情况下迷路了,这就是为什么我想得到一些帮助,任何你可以提供的工作。

我试图用PHP做这个,但我仍然得到这个错误:打开流失败:HTTP请求失败!HTTP/1.1 500内部服务器错误]

这是我的PHP代码:

<?php
$result = json_decode(file_get_contents('https://somewebsite.com/setsomedata'),true);
print_r($result);
?>

再次感谢大家

您需要使用Curl来使用该端点提供的数据。file_get_contents在某些情况下工作,但当你需要传递报头,cookie等。你需要Curl

这是一个Curl类和如何使用它的示例:

$request = new Curl($yourTargetUrlHere, [
                    'proxy' => [],
                    'headers' => [],
                ]);
$curl->go();
$response = $curl->lastRequest['response']['body']);

这是Curl

class Curl {
/** @var _ch Curl Handler Resource */
private $_ch;
/** @var _url Url to call */
private $_url;
/* Last Response. Raw result from curl */
public $lastRequest;
/* Last Request. Formatted */
public $lastResponse;
/* Errores generated */
public $errors = array();
/** @var _params Array containing data for Methods */
private $_params;
private $_cookiesJar = array();
private $_options = array();
/* Hold the number of redirections issued by Location on go() */
private $_redirections = 0;
/* HTTP Response codes. Currently not used, but usefull to have them here
in case we need to check cURL responses */
private $_codes = array(
    100 => 'Continue',
    101 => 'Switching Protocols',
    200 => 'OK',
    201 => 'Created',
    202 => 'Accepted',
    203 => 'Non-Authoritative Information',
    204 => 'No Content',
    205 => 'Reset Content',
    206 => 'Partial Content',
    300 => 'Multiple Choices',
    301 => 'Moved Permanently',
    302 => 'Found',
    303 => 'See Other',
    304 => 'Not Modified',
    305 => 'Use Proxy',
    306 => '(Unused)',
    307 => 'Temporary Redirect',
    400 => 'Bad Request',
    401 => 'Unauthorized',
    402 => 'Payment Required',
    403 => 'Forbidden',
    404 => 'Not Found',
    405 => 'Method Not Allowed',
    406 => 'Not Acceptable',
    407 => 'Proxy Authentication Required',
    408 => 'Request Timeout',
    409 => 'Conflict',
    410 => 'Gone',
    411 => 'Length Required',
    412 => 'Precondition Failed',
    413 => 'Request Entity Too Large',
    414 => 'Request-URI Too Long',
    415 => 'Unsupported Media Type',
    416 => 'Requested Range Not Satisfiable',
    417 => 'Expectation Failed',
    500 => 'Internal Server Error',
    501 => 'Not Implemented',
    502 => 'Bad Gateway',
    503 => 'Service Unavailable',
    504 => 'Gateway Timeout',
    505 => 'HTTP Version Not Supported',
);
public function __construct($url = false, $options = array())
{
    $this->_options = $options;
    return $this->browse($url, $this->_options);
}
public function __destruct()
{
    curl_close($this->_ch);
}
/**
 * Sets cURL options
 */
private function _setOpt($flag, $value)
{
    curl_setopt($this->_ch, $flag, $value);
}
/**
 * Explodes into an array a string of colon separated cookies
 *
 * @param  string $cookies   The cookies to be exploded
 * @param  string $returnKey Return only the value for the specified key
 *
 * @return array           Associative array
 */
private function _explodeCookies($cookies, $returnKey = false)
{
    if (empty($cookies))
        return;
    $newArray = array();
    foreach (explode(';', $cookies) as $value) {
        preg_match_all('/^(.*)=(.*)$/i', $value, $c);
        if (isset($c[1][0])) {
            $newArray[trim($c[1][0])] = $c[2][0];
        }
    }
    if ($returnKey) {
        return isset($newArray[$returnKey]) ? $newArray[$returnKey] : null;
    }
    return $newArray;
}
/**
 * Implodes an array of cookies into a string of cookies
 *
 * @param  array $cookies The cookies to be imploded
 *
 * @return string          The resulting string with the cookies colon separated
 */
private function _implodeCookies($cookies)
{
    $cookieStr = '';
    foreach ((array)$cookies as $key => $value) {
        if ($key) {
            $cookieStr .= $key . '=' . $value . ';';
        }
    }
    return $cookieStr;
}
/**
 * Saves cookies to _cookieJar variable
 */
private function _saveCookies()
{
    $parsedUrl = parse_url($this->_url);
    // Save cookies (always, it doesn't matter if 'session' is true or false)
    preg_match_all('|Set-Cookie: (.*);|U', $this->lastRequest['response']['headers'], $matches);
    if (!empty($matches[1])) {
        $currentCookies                        = $this->_cookiesJar[$parsedUrl['host']];
        $newCookies                            = array_merge((array)$this->_explodeCookies($currentCookies), (array)$this->_explodeCookies(implode(';', $matches[1])));
        $this->_cookiesJar[$parsedUrl['host']] = $this->_implodeCookies($newCookies);
    }
    $_SESSION['curl_cookies'][$parsedUrl['host']] = $this->_cookiesJar[$parsedUrl['host']];
}
/**
 * Merges an array recursively. Used to merge options
 */
private function _mergeRecursive(array $array1, $array2 = null)
{
    $merged = $array1;
    if (is_array($array2)) {
        foreach ($array2 as $key => $val) {
            if (is_array($array2[$key])) {
                $merged[$key] = isset($merged[$key]) && is_array($merged[$key]) ? $this->_mergeRecursive($merged[$key], $array2[$key]) : $array2[$key];
            } else {
                $merged[$key] = $val;
            }
        }
    }
    return $merged;
}
/**
 * Prepares the connection with URL and browsing options
 */
public function browse($url = false, $options = array())
{
    if (count($options)) {
        $this->_options = $this->_mergeRecursive($this->_options, $options);
    }
    $this->_options = $this->_mergeRecursive(array(
        'ua' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0',
        'cookies' => '',
        'timeout' => 30,
        'proxy' => array(
            'ip' => '',
            'port' => '',
            'username' => '',
            'password' => '',
        ),
        'ssl' => false,
        'postdata' => array(),
        'session' => true, // should we use cookies set by previous calls?
        'referer' => '',
        'headers' => array(
            'Connection: Keep-Alive',
            'Accept-Language: en-US',
            'X-Cache:',
            'X-Cache-Lookup:',
            // 'Proxy-Authorization:', // can't set this, proxy fails authentication
            // 'Accept-Encoding: gzip', // can't set this, response doesn't get unzipped
            // 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8', // can't set this on post
        ),
        'cb' => false, // callback to manipulate the options
    ), $this->_options);
    if (is_callable($this->_options['cb'])) {
        $_fn            = $this->_options['cb'];
        $this->_options = $_fn($this->_options, $this);
    }
    // Init curl
    $this->_ch = curl_init();
    if (!empty($url)) {
        $this->_url = $url;
    }
    if (!empty($this->_url)) {
        // prepare the cookie jar
        $parsedUrl                             = parse_url($this->_url);
        $this->_cookiesJar[$parsedUrl['host']] = !empty($this->_cookiesJar[$parsedUrl['host']]) ? $this->_cookiesJar[$parsedUrl['host']] : '';
        curl_setopt($this->_ch, CURLOPT_URL, $this->_url);
    }
    curl_setopt($this->_ch, CURLOPT_USERAGENT, $this->_options['ua']);
    curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true);
    // We set this to false, to grab cookies set on the request.
    // Setting to true will cause to follow redirection but the cookies wont be stored.
    // We save cookies, parse Location, and then issue a new request to the new Location
    curl_setopt($this->_ch, CURLOPT_FOLLOWLOCATION, false);
    curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, $this->_options['ssl']); // do not verify CA
    curl_setopt($this->_ch, CURLOPT_VERBOSE, true);
    curl_setopt($this->_ch, CURLOPT_HEADER, true);
    curl_setopt($this->_ch, CURLINFO_HEADER_OUT, true);
    curl_setopt($this->_ch, CURLOPT_FRESH_CONNECT, false);
    curl_setopt($this->_ch, CURLOPT_AUTOREFERER, false);
    curl_setopt($this->_ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($this->_ch, CURLOPT_TIMEOUT, $this->_options['timeout']);
    if (!empty($this->_options['referer'])) {
        curl_setopt($this->_ch, CURLOPT_REFERER, $this->_options['referer']);
    }
    // Prepare proxy
    if (!empty($this->_options['proxy']['ip'])) {
        curl_setopt($this->_ch, CURLOPT_PROXY, $this->_options['proxy']['ip']);
        curl_setopt($this->_ch, CURLOPT_PROXYPORT, $this->_options['proxy']['port']);
        curl_setopt($this->_ch, CURLOPT_PROXYTYPE, 'HTTP');
        if (!empty($this->_options['proxy']['username'])) {
            curl_setopt($this->_ch, CURLOPT_PROXYUSERPWD, $this->_options['proxy']['username'] . ':' . $this->_options['proxy']['password']);
        }
    }
    // Prepare POST data
    if (!empty($this->_options['postdata'])) {
        $this->setPost($this->_options['postdata']);
    }
    // Prepare cookies and session
    if ($this->_options['session']) {
        @session_start();
        // pull cookies that we might have in session
        if ($this->_url && !empty($_SESSION['curl_cookies'][$parsedUrl['host']])) {
            $this->_cookiesJar[$parsedUrl['host']] = $_SESSION['curl_cookies'][$parsedUrl['host']];
        }
    }
    // Prepare headers
    curl_setopt($this->_ch, CURLOPT_HTTPHEADER, $this->_options['headers']);
    return $this;
}
/**
 * Sends the request to the specified URL
 */
public function go()
{
    if (isset($this->_params['GET'])) {
        $this->_url .= '?' . $this->_params['GET'];
    }
    // Set cokies and session info here because clearCache() can be called
    // prior sending the request
    $parsedUrl = parse_url($this->_url);
    if (!empty($this->_options['cookies'])) {
        curl_setopt($this->_ch, CURLOPT_COOKIE, $this->_options['cookies']);
    } elseif ($this->_url && $this->_options['session'] && !empty($this->_cookiesJar[$parsedUrl['host']])) {
        curl_setopt($this->_ch, CURLOPT_COOKIE, $this->_cookiesJar[$parsedUrl['host']]);
    }
    try {
        $this->lastResponse = curl_exec($this->_ch);
    } catch (Exception $e) {
        $this->errors[] = $e->getMessage();
        return false;
    }
    $headerSent = curl_getinfo($this->_ch, CURLINFO_HEADER_OUT);
    // Get the headers
    $parts = explode("rnrnHTTP/", $this->lastResponse);
    $parts = (count($parts) > 1 ? 'HTTP/' : '') . array_pop($parts);
    @list($responseHeader, $responseBody) = explode("rnrn", $parts, 2);
    preg_match_all('/^Location:(.*)$/mi', $this->lastResponse, $matches);
    $location = '';
    if (!empty($matches[1])) {
        $location = trim($matches[1][0]);
    }
    // Put request in the structure
    $this->lastRequest = array(
        'request' => array(
            'headers' => curl_getinfo($this->_ch, CURLINFO_HEADER_OUT),
            'url' => $this->_url,
            'proxy' => !empty($this->_options['proxy']['ip']) ? implode(':', $this->_options['proxy']) : '',
            'body' => !empty($this->_options['postdata']) ? $this->_options['postdata'] : '',
        ),
        'response' => array(
            'headers' => $responseHeader,
            'time' => curl_getinfo($this->_ch, CURLINFO_TOTAL_TIME),
            'location' => $location,
            'info' => curl_getinfo($this->_ch),
            'body' => $responseBody,
        ),
    );
    $this->_saveCookies();
    // Follow new location redirect
    if ($this->_redirections > 10) {
        die('Loop redirection');
    }
    if (!empty($this->lastRequest['response']['location'])) {
        $this->_redirections++;
        $this->browse($this->lastRequest['response']['location'])->go();
    } else {
        $this->_redirections = 0;
    }
    return $this->lastRequest;
}
/**
 * Destroys session and clears cookies.
 */
public function clearCache()
{
    @session_destroy();
    $parsedUrl                             = parse_url($this->_url);
    $this->_cookiesJar[$parsedUrl['host']] = '';
}
/**
 * Sets the POST params to be sent
 */
public function setPost($params)
{
    $this->_params['POST'] = $params;
    curl_setopt($this->_ch, CURLOPT_POST, true);
    curl_setopt($this->_ch, CURLOPT_POSTFIELDS, is_array($this->_params['POST']) ? http_build_query($this->_params['POST']) : $this->_params['POST']);
}
/**
 * Sets the GET params to be sent
 */
public function setGet($params)
{
    $this->_params['GET'] = http_build_query($params);
}
public function getCookie($key)
{
    $parsedUrl = parse_url($this->_url);
    return $this->_explodeCookies($this->_cookiesJar[$parsedUrl['host']], $key);
}
public function debug()
{
    $this->lastRequest['response']['body'] = htmlspecialchars($this->lastRequest['response']['body'], ENT_QUOTES, 'UTF-8');
    echo '<pre>' . print_r($this->lastRequest, 1) . '</pre>';
    die();
}
}

另一种解决这个恼人的跨域AJAX问题的方法是使用。htaccess文件(您的Apache服务器需要在其上安装mod-proxy)。

RewriteEnginerewriterrule ^/setsomedata$ https://somewebsite.com/setsomedata [L,P]

我更喜欢使用Curl,对我来说似乎更容易。

对于你们所有人来说,如果你正在寻找类似的东西,你可以用这个解决方案来尝试。

    <?php
      $data = array("compraInternet" => " ", "ventaInternet" => " ", "compraAgencia" => " ", "ventaAgencia" => " ");
     $data_string = json_encode($data);
     $ch = curl_init('https://someurl.com/data');
     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
     curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array(
     'Content-Type: application/json','Content-Length: ' . strlen($data_string)));
     curl_setopt($ch, CURLOPT_TIMEOUT, 5);
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
     $result = curl_exec($ch);
     $json=json_decode($result,true);
     echo $json;
     curl_close($ch);
  ?>

最新更新