Parsing JSON from a GET response when there are headers

I am trying json_decode to get the response received from a GET request to my server API, but I am returning an empty string. Will I be right in assuming that since the response contains all the header information that the JSON decoder cannot process? This is the complete answer I get from my server:

HTTP/1.1 200 OK Server: nginx/1.0.5 Date: Sun, 18 Mar 2012 19:44:43 GMT Content-Type: application/json Connection: keep-alive Vary: Accept-Encoding X-Powered-By: Servlet/3.0; JBossAS-6 Content-Length: 97 {"pid":"162000798ab8481eaeb2b867e10f8849","uuid":"973b8722c75a4cacb9fd2316517587bb"} 

Do I need to delete headers in my servlet before sending a response to the client?

+4
source share
3 answers

Yes, json_decode should only be passed JSON data for decoding. Since you are using curl, you can simply tweak the request so that it does not return headers with something like

 curl_setopt($ch, CURLOPT_HEADER, false); 

Update: if you need headers for earlier processing, then the above will not cut. However, you can easily remove them at any time, taking advantage of the fact that there will be a double delimiter between the header and the response body. Using explode like this, then select the body:

 list(,$body) = explode("\n\n", $response, 2); 
+7
source
 json_decode(@file_get_contents('php://input'), true) 
0
source

The JSON response cannot be decoded by the header. Therefore, you need to disable the header in the response using the following code:

 curl_setopt($handle, CURLOPT_HEADER, false); 

to use any information in the header, you can use the curl_getinfo function. For example, to get the http status code, use:

 curl_getinfo($handle, CURLINFO_HTTP_CODE) 

For more information, see the reference guide here: http://php.net/manual/en/function.curl-getinfo.php

0
source

Source: https://habr.com/ru/post/1402128/


All Articles