Wednesday, July 26, 2017

Send data from Java to PHP via Post




 Here an interface between a Java and a PHP application, through we can  transfer data between the two applications. Using below java code we can generate a POST request to transfer data from JAVA to PHP.


         try {
                // open a connection to the site where script written
                URL url = new URL("http://www.domainname.com/yourphppage.php");
                URLConnection con = url.openConnection();
                // activate the output
                con.setDoOutput(true);
                PrintStream ps = new PrintStream(con.getOutputStream());
                // send your parameters to your site
                ps.print("firstKey=firstValue");
                ps.print("&secondKey=secondValue");
           
                // we have to get the input stream in order to actually send the request
                con.getInputStream();
           
                // close the print stream
                ps.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

    We can use more complex data like array to send multiple parameters and values and In your PHP script, you can get the values like this:

      foreach ($_POST as $key => $value) {
        switch ($key) {
            case 'firstKey':
                $firstKey = $value;
                break;
            case 'secondKey':
                $secondKey = $value;
                break;
            default:
                break;
        }
    }


No comments:

Post a Comment