首页 > 解决方案 > 尝试通过 PHP Curl 发送 json 时如何修复 400 Bad Request?

问题描述

我正在尝试将 json 从我的 Wordpress 发送到名为 Chorus 的法语管理服务器。

这是 API Chorus 链接,可以确切地知道我想要做什么。

卷发类

class Curl
{
    protected $url;
    protected $header = array();
    protected $data;

    public function __construct( $url, $header, $data )
    {
        $this->url = $url;
        $this->header = $header;
        $this->data = $data;
    }

    public function sendPostJsonData( string $ssl_cert = null, string $ssl_certtype = null, $ssl_keypwd = null ){
        $json_data = json_encode( $this->data, JSON_FORCE_OBJECT );
        if( isJson( $json_data ) ){
            $this->header[] = sprintf( '%s: %s', "Content-Type", "application/json" );
            $this->header[] = sprintf( '%s: %s', "Content-Length", strlen( $json_data ) );

            $ch = curl_init( $this->url );
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST" );
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data );
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1 );
            curl_setopt($ch, CURLOPT_HTTPHEADER, $this->header );
            if( !empty( $ssl_cert ) ){
                $tempPemFile = tmpfile();
                fwrite( $tempPemFile, $ssl_cert );
                $tempPemPath = stream_get_meta_data( $tempPemFile );
                $tempPemPath = $tempPemPath['uri'];
                curl_setopt( $ch, CURLOPT_SSLCERT, $tempPemPath );
            }
            if( !empty( $ssl_certtype ) )
                curl_setopt( $ch, CURLOPT_SSLCERTTYPE, $ssl_certtype );
            if( !empty( $ssl_key ) )
                curl_setopt( $ch, CURLOPT_SSLKEYPASSWD, $ssl_keypwd );
            if( ! $result = curl_exec($ch) )
            {
                $result = curl_error($ch);
            }

            curl_close( $ch );
            return $result;
        }else{
            return false;
        }
    }
}

出于某种原因,我收到了带有400 Bad Request的 HTML 响应。

原始请求

* Hostname was NOT found in DNS cache 
* Trying 185.24.185.61... 
* Connected to chorus-pro.gouv.fr (185.24.185.61) port 5443 (#0) 
* successfully set certificate verify locations: 
* CAfile: none CApath: /etc/ssl/certs 
* SSL connection using TLSv1.2 / DES-CBC3-SHA 
* Server certificate: 
* subject: C=FR; ST=93; L=Noisy Le Grand; O=AGENCE POUR L'INFORMATIQUE FINANCIERE DE L'ETAT; 2.5.4.97=NTRFR-130019771; OU=0002 130019771; serialNumber=55846EKG620; CN=chorus-pro.gouv.fr 
* start date: 2019-02-22 14:43:00 GMT 
* expire date: 2021-02-21 14:43:00 GMT 
* subjectAltName: chorus-pro.gouv.fr matched 
* issuer: C=FR; O=Certinomis; 2.5.4.97=NTRFR-433998903; CN=Certinomis - Web CA 
* SSL certificate verify ok. > POST /service-qualif/factures/soumettre HTTP/1.1 Host: chorus-pro.gouv.fr:5443 Compte technique:TECH_1111111111@cpp2017.fr Mot de passe:MyPWD Certificat:-----BEGIN PKCS7----- CERTIFICATE CONTENT -----END PKCS7----- Content-Type: application/json Accept: application/json Content-Length: 2193 Expect: 100-continue < HTTP/1.1 400 Bad Request < Date: Mon, 30 Dec 2019 17:23:06 GMT < Content-Length: 226 < Connection: close < Content-Type: text/html; charset=iso-8859-1 < 
* Closing connection 0 

我的问题是:

  1. 使用 PHP Curl 发送 json 得到这种错误的不同可能性是什么
  2. 如何获得更好的错误消息来解决我的问题?

标签: phpjsoncurlbad-request

解决方案


如果您想为您的服务提供“漂亮”的响应,您可以查看 3rd 方服务的响应代码。您可以使用 try catch 来防止错误并在您的消息中返回受控响应

在 sendPostJsonData 函数中检查响应状态

if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
    throw new Exception('Invalid response');
}

并在执行结束时发起不同的响应

try {
    ...
    $result = $curl->sendPostJsonData();
    ...
} catch (Exception $e) {
    echo json_encode(array(
        'status' => 'error',
        'msg' => 'your pretty response'
    ));
}

推荐阅读