【问题标题】:Send POST request with PHP使用 PHP 发送 POST 请求
【发布时间】:2021-11-30 14:44:02
【问题描述】:

对于我想使用的翻译工具,我需要在每个 POST 中发送我的请求。 我从来没有做过这样的事情,文档对我来说意义不大(它不是特定于 php 的文档,也不知道如何在 php 中实现)

文档中的示例是:

POST /v2/translate HTTP/1.0
Host: api.deepl.com
Accept: */*
User-Agent: YourApp
Content-Type: application/x-www-form-urlencoded
Content-Length: 91

auth_key=MYKEY&text=this%20is%20a%20test&target_lang=de

在 stackoverflow 的另一篇文章中,我发现了在 php 中使用 POST 的解决方案, 所以我的主要问题是,我不确定一切都在哪里 我假设 Host 进入 url 并且该标题是正确的。不过就我有限的技术能做到的就这么多

$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

任何帮助将不胜感激

【问题讨论】:

  • 您最好使用curl 发送 POST 请求。

标签: php post deepl


【解决方案1】:

您可以在 PHP 中使用 curl 发出 POST 请求。

// initiate the curl request
$request = curl_init();

curl_setopt($request, CURLOPT_URL,"http://www.otherDomain.com/getdata");
curl_setopt($request, CURLOPT_POST, 1);
curl_setopt($request, CURLOPT_POSTFIELDS,
        "var1=value1&var2=value2");

// catch the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($request);

curl_close ($request);

// do processing for the $response

【讨论】:

  • 谢谢,出于某种原因,我认为 curl 是一个单独的东西(并且与发送帖子无关)所以学到了一些新东西,谢谢!
猜你喜欢
  • 2017-07-13
  • 2011-08-04
  • 2017-05-31
  • 1970-01-01
  • 2012-08-31
  • 1970-01-01
相关资源
最近更新 更多