【发布时间】:2015-06-30 22:02:22
【问题描述】:
我正在尝试在我的 PHP 文件中执行各种语句/查询,具体取决于接收到的变量(此外,有没有办法发送变量并选择我想要执行的查询类型,而不是进行一次查询对于收到的每组变量?这是我第一次用 PHP 编写,所以请原谅可能的愚蠢问题)。
在这种情况下,它是用户名、密码和用户 ID。我希望在收到这 3 个变量时进行插入。但是,我不断收到错误消息:java.net.ProtocolException:方法不支持请求正文:GET(这是 conn.setDoOutput 设置为 true 时)。如果我将其设置为 false,我会收到一个 IO URL 错误,指出无法找到我的 URL。我究竟做错了什么?下面是我的 php 脚本和用于 GET 请求的 java 代码。
<?php
$con=mysqli_connect("logindetailsgohere");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_GET['Username']) && isset($_Get['Password']) && isset($_GET['UserID'])){
$uname = mysql_real_escape_string($_GET['Username']);
$pass = mysql_real_escape_string($_GET['Password']);
$uid = intval($_GET['UserID']);
$sql = "INSERT IGNORE INTO Users (id, Username, Password) VALUES ('$uid', '$uname', '$pass')";
if(mysqli_query($con, $sql){
echo "Values have been inserted";
}
}
mysqli_close($con);
?>
Java 代码:
public String connect() {
try {
/*URL url = new URL("phpfilelocation.php");*/
String data = URLEncoder.encode("un", "UTF-8") + "=" + URLEncoder.encode(un, "UTF-8");
data += "&" + URLEncoder.encode("pw", "UTF-8") + "=" + URLEncoder.encode(pw, "UTF-8");
data += "&" + URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(uid), "UTF-8");
URL url = new URL("phpfilelocation.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "fail";
}
【问题讨论】:
-
您是否尝试过打印您的请求字符串以查看 URLEncoder 是否实际编码正确?我过去遇到过一些奇怪的行为,不得不添加一些额外的方法来确保正确的编码。
-
`wr.write(data); - 这是 URLConnection 抱怨的(部分)。下定决心:GET(将数据直接附加到 url 字符串)或 POST(将数据写入请求正文/输出流)。