About Me

My photo
India
Hey there, lovely people! I'm Hemant Menaria, and I'm passionate about programming. Having completed my MCA in 2011, I've delved into the world of coding with fervor. I believe in sharing knowledge, making complex concepts easy to grasp for everyone. JAVA, PHP, and ANDROID hold a special place in my heart, and I spend most of my time immersed in them. Currently, I'm deeply engaged in API/Webservice frameworks and crafting Hybrid mobile applications to enhance flexibility in the digital realm. If you ever find yourself stuck with a programming challenge, feel free to reach out to me at +91-8955499900 or drop me a line at hemantmenaria008@gmail.com. I'm always eager to help fellow enthusiasts navigate the intricacies of coding!

Thursday, December 3, 2015

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