Martin
Martin

Reputation: 131

How to pass value from java to PHP?

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";
}
?>

Upvotes: 4

Views: 3174

Answers (3)

Martin
Martin

Reputation: 131

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.

Upvotes: 1

Ruslan Stelmachenko
Ruslan Stelmachenko

Reputation: 5420

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.

Upvotes: 2

Jay S.
Jay S.

Reputation: 1327

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.

Upvotes: 0

Related Questions