【发布时间】:2015-09-28 05:20:03
【问题描述】:
编辑:我发现将 OutputStreamWriter 包装在 BufferedWriter 中会导致问题,因此去掉了包装器,我的 POST 也通过了。仍然想知道为什么是 BufferedWriter。
我提前道歉,因为我刚刚开始自学有关数据库、应用程序和服务器/数据库之间的通信以及 php 的所有知识。
提出的其他类似问题未提供答案。
在使用 HttpUrlConnection 从我的 android 应用程序到本地托管服务器上的 php 脚本进行简单 POST 时,我很难辨别我缺少什么。我需要从 android 应用程序中获取用户 ID,将其作为参数传递给 php 脚本,然后在名为 users 的数据库表中查找该 ID。我也想使用未被弃用的方法和类。
我已在 android 清单中包含 Internet 权限。我正在使用 XAMPP,并且我已验证我的服务器正在运行,如果我通过 Web 浏览器访问该 url,我会得到我正在寻找的 JSON 响应。
我唯一的 logcat 消息是 IOException,它在写入输出流之后发生。 编辑: 具体的例外是“流的意外结束”。
这是我的 AsyncTask 类中的代码:
protected String doInBackground(String... params) {
String userID = params[0];
Pair<String, String> phpParameter = new Pair<>("userID", userID);
String result = "";
try {
URL url = new URL("url of locally-hosted php script");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// prepare request
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setFixedLengthStreamingMode(userID.getBytes("UTF-8").length);
// upload request
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(phpParameter.first + "=" + phpParameter.second);
writer.close();
outputStream.close();
// read response
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) { response.append(inputLine); }
in.close();
result = response.toString();
// disconnect
urlConnection.disconnect();
} catch (MalformedURLException e) {
Log.e("Malformed URL Exception", "Malformed URL Exception");
} catch (IOException e) {
Log.e("IOException", "IOException");
}
return result;
}
这是我在服务器上的 php 脚本。我还需要一些关于准备好的陈述的帮助,所以不要因为“id = 1”而责备我:
<?php
mysql_connect("host","username","password");
mysql_select_db("Database");
print($_POST);
$sql = mysql_query("select * from users where id = 1");
while($row = mysql_fetch_assoc($sql))
$output[] = $row;
print(json_encode($output)); // this will print the output in json
mysql_close();
?>
【问题讨论】:
-
only logcat message is an IOException, which occurs just after writing to the output stream。那么你应该准确地发布哪个异常。 -
您使用
Log.e()错误,这就是您没有获得所需信息的原因。它应该类似于Log.e("MyClassName", "my description of what went wrong", e) -
@Dan Getz 哇,抱歉。我完全糊涂了将实际异常传递给日志。我得到“流的意外结束”。包括上面的修改以反映这一点!
标签: php android post httpurlconnection