如何从Java中调用的php文件中获取返回值

时间:2013-07-17 22:16:10

标签: java php httpurlconnection

我在Java(而不是Javascript)中使用HttpURLConnection来调用PHP文件,该文件在mySQL数据库中查找字段。在PHP中如何返回字段内容(String),在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);

?>

2 个答案:

答案 0 :(得分:2)

我能想到的最简单的方法是输出“data”字段的内容后跟换行符(假设data当然不包含换行符),这样BufferedReader的readLine()方法就可以了使用。

php方面:

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

Java方面:

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

当然需要一些额外的错误检查,但这是本质。您还可以使用例如JSON或XML格式序列化data的内容,并在Java端反序列化,但看起来像一个很可能过度的简单用例。

答案 1 :(得分:1)

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

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

...

您还需要在PHP文件中输出一些内容,感兴趣的字段上的简单echo将在响应时输出。