我正在尝试将两个字符串值从我的 java 程序发送到我的 php 页面,但我似乎很难弄清楚这一切是如何工作的。
public static void main (String args[]) throws IOException{
Scanner input = new Scanner (System.in);
String sampleValue = input.next();
String sampleValue1 = input.next();
URL url = new URL("http://woah.x10host.com/randomfact.php");
String result = "";
String data = "fName=" + URLEncoder.encode(sampleValue, "UTF-8");
String id = "lName=" + URLEncoder.encode(sampleValue1, "UTF-8");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// Send the POST data
DataOutputStream dataOut = new DataOutputStream(connection.getOutputStream());
dataOut.writeBytes(id);
dataOut.writeBytes(data);
dataOut.flush();
System.out.println("Data has been posted");
dataOut.close();
BufferedReader in = null;
try {
String line;
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = in.readLine()) != null) {
result += line;
}
} finally {
if (in != null) {
in.close();
}
}
} finally {
connection.disconnect();
System.out.println(result);
}
}
我的PHP代码是
<?php
$conn = mysqli_connect("localhost","woahx10h_funfact","spk","woahx10h_woah");
// CHECK CONNECTION
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$value_data = $_POST['fName'];
$value_id = $_POST['lName'];
echo $value_data;
echo $value_id;
$conn->close();
?>
但是,每次我运行 java 程序时,data 和 id 的值似乎都存储在 $value 中。我希望数据中的值存储在 $value_data 中,而 x 中的值存储在 $value_id 中
最佳答案
您必须在每两个参数之间添加符号 (&)。所以在这种情况下,您所要做的就是像这样编辑您的代码:
...
dataOut.writeBytes(id);
dataOut.writeBytes("&");
dataOut.writeBytes(data);
...
如果您想向请求添加另一个参数,则必须添加另一个与号,然后再添加参数,例如:
...
dataOut.writeBytes(id);
dataOut.writeBytes("&");
dataOut.writeBytes(data);
dataOut.writeBytes("&");
dataOut.writeBytes(parameter3);
...
关于java - 使用java将两个值发送到php网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32641597/