How to pass value from java to PHP?

3.1k views Asked by At

I am trying to pass a value from java class to PHP file on the server to test this value and reply to java. The problem it returns null value.

Java Code

package phpJava;
import java.io.*;
import java.net.URL;
import javax.swing.JOptionPane;
public class phpbirgde {
public static void main(String[] args) {
        try{
            String erg = JOptionPane.showInputDialog("2+3");
            BufferedReader br = new BufferedReader(new InputStreamReader(new URL("http://localhost//test.php?test="+erg).openStream()));
                    String b = br.readLine();
                    System.out.println(b); // print the string b
                    if(b.equalsIgnoreCase("true")){
                        System.out.println("It is true");
                    }
                    else {
                        System.out.println("False");
                    }

            } catch(IOException e){
                System.out.println("error");
            }
}

    }

PHP Code

 <?php
 $test = $_GET['test'];
 if($test =="5"){
 echo "true";
 }
 else {
 echo "false";
}
?>
3

There are 3 answers

0
Jay S. On

Try the URL and URLConnection classes

String loc = "http://localhost//test.php?test="+erg;
URL url = new URL(loc);
URLConnection con = url.openConnection();
InputStream i = con.getInputStream();

Otherwise, your PHP looks OK.

0
Ruslan Stelmachenko On

It is by contract:

public String readLine() throws IOException

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Returns:

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

In your case the php script just outputs true string (without \n) into the output stream and closes the connection.

So, add the \n (echo "true\n";) on PHP side, or use another method to read the response from Java side.

1
Martin On

The problem was I have put a space before the php tag in PHP file and it was returning the space only. Now this code works perfectly.