Sending post message to PHP server using java/groovy

Issue

Good afternoon everyone.

I’m new in using both java/groovy and PHP and was working on a attempting a basic method to send a json message to the a php file.

I have a php file which is as follows

<?php
 
    $query = "Hi, my name is: '".$_POST["name"]."'";
    echo $query;
    
?>

and my java/groovy file is as follows

post = (new URL("http://localhost/Ping/Post.php")).openConnection()

message =  '{"name":"Max Weiver"}';

println("This is the message = "+message);

post.setRequestMethod("POST");

post.setRequestProperty("Content-Type","application/json");

post.setDoOutput(true);

post.getOutputStream().write((message).getBytes("UTF-8"));

println("This is the detailed message: "+post);

postResponseCode = post.getResponseCode();

println "Response Code: ${postResponseCode}"

postResponseData = post.getInputStream().getText();


println "Response Data: ${postResponseData}"

And I just want the groovy console to output something like this

Hi, my name is: 'Max Weiver'

However, I keep getting this error:

Response Code: 200
Response Data: <br />
<b>Notice</b>:  Undefined index: name in <b>C:\xampp\htdocs\Ping\Post.php</b> on line <b>3</b><br />
Hi, my name is: ''

I’m aware that there are solutions to be made within the php file to sort this problem (like using the json_decode and the isset, etc). But I’m wondering whether there modification needed within the groovy/java file to successfully send the POST message without changing the php script?

*Note: As I said earlier, I’m sort of new in both languages so do let me know if I’m missing something obvious 🙂

Thank you

Solution

In php _POST is an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

https://www.php.net/manual/en/reserved.variables.post.php

to make groovy call successful the easiest way to pass parameters in
application/x-www-form-urlencoded format:

name1=value1&name2=value2&...

changed groovy code:

def post = new URL("http://httpbin.org/post").openConnection()
def body =  [name: "Max Weiver"]
//convert map to x-www-form-urlencoded
body = body.collect{k,v-> "$k=${URLEncoder.encode(v,'UTF-8')}" }.join('&')

println("This is the body = "+body);

post.setRequestMethod("POST")
post.setRequestProperty("Content-Type","application/x-www-form-urlencoded")
post.setDoOutput(true)
post.getOutputStream().write(body.getBytes("US-ASCII"))

def postResponseCode = post.getResponseCode()
println "Response Code: ${postResponseCode}"

def postResponseData = post.getInputStream().getText()
println "Response Data: ${postResponseData}"

Answered By – daggett

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published