?
Solved

how to call php script in java

Posted on 2012-04-02
11
Medium Priority
?
431 Views
Last Modified: 2012-08-13
hello - i would like to know how to call a php script from java applet.

outcome - passing java parameters to php

can you provide a working example?

thanks in advance for your help!
0
Comment
Question by:only1wizard
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 2
11 Comments
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 37796083
For something like this, I think I would set the PHP script up as a web service and call it via a RESTful interface.  Basically, the PHP script would have its own URL and you would pass the parameters to the URL as part of the query string.  This makes it easy to test the web service because you can just type the URL into a browser address bar and see the results.  See this code snippet as an example of a PHP web service.
<?php // RAY_REST_get_last_name.php
error_reporting(E_ALL);



// DEMONSTRATE HOW A RESTFUL WEB SERVICE WORKS
// INPUT FIRST NAME, OUTPUT FAMILY NAME
// CALLING EXAMPLE:
// file_get_contents('http://laprbass.com/RAY_REST_get_last_name.php?key=ABC&resp=XML&name=Ray');



// OUR DATA MODEL CONTAINS ALL THE ANSWERS - THIS COULD BE A DATA BASE - AS SIMPLE OR COMPLEX AS NEEDED
$dataModel
= array
( 'Brian'   => 'Portlock'
, 'Ray'     => 'Paseur'
, 'Richard' => 'Quadling'
, 'Dave'    => 'Baldwin'
)
;


// RESPONSE CAN BE PLAIN TEXT OR XML FORMAT
$alpha = NULL;
$omega = NULL;
if ( (isset($_GET["resp"])) && ($_GET["resp"] == 'XML') )
{
    // PREPARE THE XML WRAPPER
    $alpha = '<response>';
    $omega = '</response>';
}



// TEST THE 'API KEY' - THIS COULD BE A DATA BASE VALIDATION LOOKUP - AS SIMPLE OR COMPLEX AS NEEDED
$key = (!empty($_GET["key"])) ? $_GET["key"] : FALSE;
if ($key !== 'ABC')
{
    echo $alpha . 'BOGUS API KEY' . $omega;
    die();
}



// LOOK UP THE FAMILY NAME
$name = (!empty($_GET["name"])) ? $_GET["name"] : 'UNKNOWN';

// IF THE NAME FROM THE URL IS FOUND IN THE DATA MODEL
if (array_key_exists($name, $dataModel))
{
    // RETURNS THE APPROPRIATE FAMILY NAME FROM THE DATA MODEL
    echo $alpha . $dataModel[$name] . $omega;
    die();
}

// RETURNS THE UNKNOWN NAME INDICATOR
else
{
    echo $alpha . 'UNKNOWN' . $omega;
    die();
}

Open in new window

0
 

Author Comment

by:only1wizard
ID: 37796116
do you have an example of java applet that would pass the java variable to php script?

thanks in advance for your help!
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37796224
No, I only have the PHP side.  Leave the question open for a while and maybe a Java programmer will come along with the other half of the solution!
0
Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

 

Author Comment

by:only1wizard
ID: 37796245
ok will do thank u
0
 

Author Closing Comment

by:only1wizard
ID: 37800658
thanks for your example of the web service!

i have solved this problem the java works fine it was the php. solution i resolved the problem by focusing on getting the php script working alone with out the java once it ran on its own i recompiled java and ran the file and it works.

thanks in advance for your help!
0
 
LVL 10

Expert Comment

by:gordon_vt02
ID: 37800663
Take a look at the java.net.URL and java.net.HttpURLConnection classes.  You should be able to use those to call the PHP web service and pass whatever parameters are required, then read the response as an InputStream in your applet.  If the PHP service is not located on the same web server, you'll have to sign your applet or you won't be able to communicate with it.

Sample use of HttpURLConnection:
public Object queryService(Object param1, Object param2) {
    String encParam1 = URLEncoder.encode(param1.toString(), "UTF-8");
    String encParam2 = URLEncoder.encode(param2.toString(), "UTF-8");
    URL serviceURL = new URL(String.format("http://www.yourserver.com/webService.php?param1=%s&param2=%s", encParam1, encParam2));
    HttpURLConnection conn = (HttpURLConnection)serviceURL.openConnection();
    // check response code -- if OK, proceed with processing output, otherwise handle errors
    int responseCode = conn.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        InputStream response = conn.getInputStream();
        // read from the input stream and process results appropriately
    } else {
        // check error code and take appropriate actions
    }
    conn.close();
}

Open in new window


I left out the exception handling, but you'll need to account for those as well.  Mostly subclasses of IOException, but there are some others as well (MalformedURLException for one).  Hope that helps!
0
 

Author Comment

by:only1wizard
ID: 37800744
oh here is my java code

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * Send a POST request using URLConnection
 * (Consider using HttpURLConnection or HttpsURLConnection)
 */

/**
 *
 * @author theodore werntz ii
 */
public class WebClientPHP {
    
public static void main(String[] args) {
        
        try {
            // Prepare data
            String data = "testData" ; // grab users session id
                              
            // Prepare connection
            URL url = new URL("http://127.0.0.1/subtest.php?name="+ data );
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);  // Needed to write to a URLConnection
            
             // Get the response
            BufferedReader reader = new BufferedReader(
                                          new InputStreamReader(
                                                connection.getInputStream()));
            // Print the response
            String line;
            while ((line = reader.readLine()) != null)
                System.out.println(line);
            
            reader.close();  // Close the reader
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Open in new window


just thought i would share the java code as well

thanks in advance for your help!
0
 
LVL 10

Expert Comment

by:gordon_vt02
ID: 37801137
Make sure you URLEncode the parameter string, just in case there are any reserved characters.  Unless you are planning on pushing data to the connection, there's no need to call connection.setDoOutput(true).  That would only be necessary if you were calling connection.getOutputStream() and writing data to it.
0
 

Author Comment

by:only1wizard
ID: 37801289
can i have multiple strings i.e.

String data = <?php $_SESSION['UserName'] ?>;
String UserId = <?PHP $_SESSION['UserId'] ?>;

i will encode the params just gave that as an example.

then i will reference them i.e.

URL url = new URL("http://localhost/subtest.php?name=" + data + "&id=" +UserId);

thanks in advance for your help!
0
 
LVL 10

Expert Comment

by:gordon_vt02
ID: 37802594
Yep.  That should work.  Especially with multiple parameters, I'd recommend going the String.format() route for the URL.  Easier to read than String concatenation and more efficient as well.

URL url = new URL(String.format("http://localhost/subtest.php?name=%s&id=%s", data, UserId);

Open in new window

0
 
LVL 10

Expert Comment

by:gordon_vt02
ID: 37802596
Oops... forgot the closing ) above.
0

Featured Post

Tutorials alone can't teach real engineering

So we built better training tools.

-Hands-on Labs
-Instructor Mentoring
-Scenario-Based Tests
-Dedicated Cloud Servers

All at your fingertips. What are you waiting for?

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses
Course of the Month12 days, 13 hours left to enroll

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question