Post form data to java server using php curl

Recently one of client come up with the requirements to post data from php platform to java platform. We thought it would be simpler task as we need to fetch data from mysql database and need to do http post to the java server. We can use the php curl and post the data to java server. Simple stuff !!! right ? Well not exactly. We tried to use the php curl and used array to send the data to server. To our surprise, data was not captured by java server. We were using the following code to post form data to java server:

define("URL","http://Yoursite.com:8080/action.do");

$fields = array(
  'lname'=>$last_name,
  'fname'=>$first_name,
  'title'=>$title,
  'company'=>$institution,
  'age'=>$age,
  'email'=>$email,
  'phone'=>$phone
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$output = curl_exec($ch);
curl_close($ch);

We tried to investigate the problem and our first suspicion was that the php curl is not working properly. We create a php script which just listens the request and print all the parameters in the log file.We used the above code and we were able to extract the parameters from the request. So it was the time we ask our friends google and stackoverflow. We read many articles and documentations but there were no solution for this problem. Later we realized that java server is not unmarshalling the post data(mutipart/form-data) which is in array format from php curl. So we decided to use other approach i.e. send the parameters in urlencoding string as we have http servlet on the java server side.


We hope this would help other developers to resolve this type of issue. Alternative solution to resolve this issue is to add support for multipart/form-data on java server using common’s ServletFileUpload
Please let us know your questions.

Related Posts

Post form data to java server using php curl was last modified: April 11th, 2016 by Kapil Jain