[当尝试通过PHP Curl发送json时如何解决400错误请求?

问题描述 投票:0回答:1

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

This is the API Chorus link to know exactly what I want to do.

卷曲类

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响应。

原始请求

POST /service-qualif/factures/soumettre HTTP/1.1 
Host: chorus-pro.gouv.fr:5443 
Compte technique:[email protected] 
Mot de passe: MYPWD 
Certificat:-----BEGIN PKCS7----- MY CERTIFICATE CONTENT -----END PKCS7----- 
Content-Type: application/json 
Accept: application/json 
Content-Length: 2193 
Expect: 100-continue

我的问题是:

  1. 使用PHP Curl发送json来获得这种错误的可能性有哪些?
  2. 如何获得更好的错误消息来解决我的问题?

我正在尝试将WordPress中的json发送到名为Chorus的法语管理服务器。这是API Chorus链接,可以确切地知道我要做什么。 Curl类class Curl {受保护的$ ...

php json curl bad-request
1个回答
-1
投票

如果您希望服务获得“漂亮”的响应,则可以检查第三方服务的响应代码。您可以使用try catch来防止错误并通过邮件返回受控回复

© www.soinside.com 2019 - 2024. All rights reserved.