breathe0
breathe0

Reputation: 593

Slow HTTP POST request in php

I'm trying to POSTing some data (a JSON string) from a php script to a java server (all written by myself) and getting the response back. I tried the following code:

$url="http://localhost:8000/hashmap";
$opts = array('http' => array('method' => 'POST', 'content' => $JSONDATA,'header'=>"Content-Type: application/x-www-form-urlencoded"));
$st = stream_context_create($opts);
echo file_get_contents($url, false,$st);

Now, this code actually works (I get back as result the right answer), but file_get_contents hangs everytime 20 seconds while being executed (I printed the time before and after the instruction). The operations performed by the server are executed in a small amount of time, and I'm sure it's not normal to wait all this time to get the response. Am I missing something?

Upvotes: 2

Views: 4993

Answers (2)

DaveRandom
DaveRandom

Reputation: 88677

Try adding Connection: close and Content-Length: strlen($JSONDATA) headers to the $opts.

Also, if you want to avoid using extensions, have a look at this class I wrote some time ago to perform HTTP requests using PHP core only. It works on PHP4 (which is why I wrote it) and PHP5, and the only extension it ever requires is OpenSSL, and you only need that if you want to do an HTTPS request. Documented(ish) in comments at the top.

Supports all sorts of stuff - GET, POST, PUT and more, including file uploads, cookies, automatic redirect handling. I have used it quite a lot on a platform I work with regularly that is stuck with PHP/4.3.10 and it works beautifully... Even if I do say so myself...

Upvotes: 0

OneOfOne
OneOfOne

Reputation: 99284

Badly mis-configured server maybe that doesn't send the right content-size and using HTTP/1.1.

Either fix the server or request the data as HTTP/1.0

Upvotes: 2

Related Questions