bstrong
bstrong

Reputation: 660

How do you get a return value from a php file called in Java

I'm using HttpURLConnection in Java (not Javascript) to call a PHP file which looks up a field in a mySQL database. In PHP how do I return the field contents (String) and in Java how do I receive them? Thank you. Awesome points to any who can help. Lol.

Sample code:

Java:

import java.net.HttpURLConnection;
import java.net.URL;
...
public static void Connect(String address){
    URL url = new URL("http://www.foo.com/getInfo.php?id=203&user=johndoe);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    String = ??? // What do I need to do to get the string from the PHP file?
    con.disconnect();
}

PHP:

<?php

$theFile = "../db_user_password";
$f = fopen($theFile, 'r') or die("Could not access password file.");
$user = chop(fgets($f));
$pass = chop(fgets($f));
$name = chop(fgets($f));
if (strlen($name) == 0) {
    $name = 'some_db';
}
fclose($f);

$connect = mysql_pconnect("localhost", $dbuser, $dbpass) or
        die('Could not connect: ' . mysql_error());

mysql_select_db($name, $connect) or die("Could not find database");

$id = urldecode($_GET['id']);
$user = urldecode($_GET['user']);

$query = "SELECT data FROM autosave_table WHERE id='$id' AND user='$user';
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);

$updateQuery = "";
if ($num_rows == 1) {
    //What do I put here to return a string from data?
}

mysql_query($updateQuery);

?>

Upvotes: 1

Views: 3078

Answers (2)

fvu
fvu

Reputation: 32983

The simplest way I can think of is to just output the "data" field's content followed by a newline (assuming data won't contain newlines of course), so that BufferedReader's readLine() method can be used.

php side:

if ($num_rows == 1) {
    $row = mysql_fetch_assoc($result);
    printf("%s\n",$row['data']);
}

Java side:

BufferedReader in = new BufferedReader(new InputStreamReader(
                                con.getInputStream()));
String message = in.readLine();
in.close();

Needs some extra error checking of course, but this is the essence. You could also serialize the content of data in eg JSON or XML format, and deserialize that on the Java side, but for what looks like a simple use case that's very probably overkill.

Upvotes: 2

Sam Aleksov
Sam Aleksov

Reputation: 1201

InputStream inputStream = new BufferedInputStream(con.getInputStream());

Scanner scanner = new java.util.Scanner(inputStream);
String response = "";
while (scanner.hasNextLine())
{
     response += scanner.nextLine();
}

...

You also need to output something in the PHP file, a simple echo on the interested fields will do it as it outputs on the response.

Upvotes: 1

Related Questions