Viewed   239 times

Does anybody know the correct way to post JSON using Guzzle?

$request = $this->client->post(self::URL_REGISTER,array(
                'content-type' => 'application/json'

I get an internal server error response from the server. It works using Chrome Postman.



For Guzzle <= 4:

It's a raw post request so putting the JSON in the body solved the problem

$request = $this->client->post(
        'content-type' => 'application/json'
$request->setBody($data); #set body!
$response = $request->send();
Tuesday, November 29, 2022

You have to specify stream and sink options like this:

$res = $client->request('GET', 'http://localhost:3002/', [
    'stream' => true,
    'sink' => STDOUT, // Default output stream.
    'on_headers' => ...

After these additions you will be able to stream responses chunk by chunk, without any additional code to copy from response body stream to STDOUT (with echo).

But usually you don't want to do this, because you will need to have one process of PHP (php-fpm or Apache's mod_php) for each active client.

If you just want to serve secret files, try to use an "internal redirect": through X-Accel-Redirect header for nginx or X-Sendfile for Apache. You will get the same behavior, but with less resource usage (because of high optimized event loop in case of nginx). For configuration details you can read an official documentation or, of course, other SO questions (like this one).

Monday, August 22, 2022

You have to use headers config sections for headers, not the root level.

return new Client([
    'base_uri' => env('API_HOST'),
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'Bearer ' . $token,
        'Content-Type' => 'application/json',
Thursday, August 18, 2022

Usual way is to use a HashMap with Key-value pair as request parameters with Volley

Similar to the below example, you need to customize for your specific requirement.

Option 1:

final String URL = "URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "token_value");
params.put("login_id", "login_id_value");
params.put("UN", "username");
params.put("PW", "password");

JsonObjectRequest request_json = new JsonObjectRequest(URL, new JSONObject(params),
       new Response.Listener<JSONObject>() {
           public void onResponse(JSONObject response) {
               try {
                   //Process os success response
               } catch (JSONException e) {
       }, new Response.ErrorListener() {
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());

// add the request object to the queue to be executed

NOTE: A HashMap can have custom objects as value

Option 2:

Directly using JSON in request body

try {
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    String URL = "http://...";
    JSONObject jsonBody = new JSONObject();
    jsonBody.put("firstkey", "firstvalue");
    jsonBody.put("secondkey", "secondobject");
    final String mRequestBody = jsonBody.toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        public void onResponse(String response) {
            Log.i("LOG_VOLLEY", response);
    }, new Response.ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            Log.e("LOG_VOLLEY", error.toString());
    }) {
        public String getBodyContentType() {
            return "application/json; charset=utf-8";

        public byte[] getBody() throws AuthFailureError {
            try {
                return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
      "Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                return null;

        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String responseString = "";
            if (response != null) {

                responseString = String.valueOf(response.statusCode);

            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));

} catch (JSONException e) {
Friday, August 12, 2022

As mentioned cookies are in HTTP::Cookies:

  • You need to create a cookie jar

  • You set the value of the cookies to put in the jar

  • You then associate that jar with your user agent

For example:

my $ua = LWP::UserAgent->new;
my $cookies = HTTP::Cookies->new();
$cookies->set_cookie(0,'cookiename', 'value','/','',80,0,0,86400,0);
# Now make your request

set_cookie has a rather large number of arguments:

set_cookie( $version, $key, $val, $path, $domain, $port, $path_spec, $secure, $maxage, $discard, %rest )

This is because the cookie jar is designed from the point of view of a browser (a UserAgent), rather than a single request. This means not all the arguments are so important in this case.

The ones you need to get right are $key, $val, $path, $domain, $port.

Regarding the:

500 Can't connect to (Bad hostname '')

It means that LWP can't lookup the address for Google. Are you behind a web proxy? If so you will need to set your proxy in the UA too using something like:

$ua->proxy(['http', 'https'], '');

Monday, August 15, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :