我一直在尝试使用一个简单的 POST 请求向 MySQL 数据库添加一些基本信息,但我似乎运气不佳 - 它不会将元组添加到数据库中。我知道这段代码运行它请求的 PHP 文件,就好像我告诉 PHP 文件将虚拟信息添加到它工作正常的数据库一样,但是 POST 字符串中的信息没有被添加。
这是我的Java文件:
public class Test {
public static void main(String[] args) {
int id = 3696;
String name = "David";
int steps = 6989;
String strData = encode(id, name, steps);
submit(strData);
}
public static String encode(int id, String name, int steps) {
String strToSend;
try
{
strToSend = URLEncoder.encode("id", "UTF-8") + "=";
strToSend += URLEncoder.encode("" + id, "UTF-8");
strToSend += "&" + URLEncoder.encode("name", "UTF-8") + "=";
strToSend += URLEncoder.encode(name, "UTF-8");
strToSend += "&" + URLEncoder.encode("steps", "UTF-8") + "=";
strToSend += URLEncoder.encode("" + steps, "UTF-8");
}
catch (Exception e) {
return "Error encoding data for submission";
}
return strToSend;
}
public static String submit(String strToSend) {
URL urlDest;
String strData = strToSend;
System.out.println(strData);
HttpURLConnection ucConnect;
try
{
urlDest = new URL("http://localhost/~David/posttest.php");
}
catch (Exception e)
{
return "Error in submitting entry";
}
try
{
ucConnect = (HttpURLConnection) urlDest.openConnection();
ucConnect.setRequestProperty("Content-type","application/x-www-form-urlencoded");
ucConnect.setRequestMethod("POST");
ucConnect.setDoOutput(true);
}
catch (Exception e)
{
return "Error in connecting to URL";
}
try
{
OutputStreamWriter streamWrite = new OutputStreamWriter(ucConnect.getOutputStream());
streamWrite.write(strData);
System.out.println(streamWrite.toString());
streamWrite.flush();
//Get the response
ucConnect.getInputStream();
System.out.println(ucConnect);
streamWrite.close();
}
catch (Exception e)
{
return "Problem";
}
System.out.println("SUCCESS");
return "Yay!";
}
}
这是 posttest.php
<?php
$con=mysqli_connect(removed);
//check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST["id"];
$strName = $_POST["name"];
$noSteps = $_POST["steps"];
mysqli_query ($con, "INSERT INTO People VALUES ($id, $strName, $noSteps)" || die();
mysqli_close($con);
echo json_encode($arr);
?>
我发送的字符串的打印格式是:
id=3696&name=David&steps=6989
谢谢您的帮助。