How to pass value from java to PHP?

I am trying to transfer a value from a java class to a PHP file on the server in order to check this value and respond to java. The problem returns null.

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";
}
?>
+4
source share
3 answers

This is the contract :

public String readLine() throws IOException

Reads text. A line is considered terminated by any ('\ n'), carriage return ('\ r') or carriage return, after which a line is immediately returned.

Returns

A String containing the contents of the string, not including any line termination characters, or null if the end of the stream is reached

php script true ( \n) .

, \n (echo "true\n";) PHP Java.

+2

, php PHP, . .

+1

Try 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 fine.

0
source

Source: https://habr.com/ru/post/1665478/


All Articles