我希望打开一个URL并提交以下参数,但只有当我添加BufferedReader到我的代码中,它才有效。为什么会这样?
Send.php是一个将用户名和时间添加到我的数据库的脚本。
以下代码不起作用(不会向数据库提交任何数据):
但是这段代码确实有效:
Send.php是一个将用户名和时间添加到我的数据库的脚本。
以下代码不起作用(不会向数据库提交任何数据):
final String base = "http://awebsite.com//send.php?";
final String params = String.format("username=%s&time=%s", username, time);
final URL url = new URL(base + params);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Agent");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
但是这段代码确实有效:
final String base = "http://awebsite.com//send.php?";
final String params = String.format("username=%s&time=%s", username, time);
final URL url = new URL(base + params);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Agent");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
connection.disconnect();
Apache HttpClient
是一个非常不错的选择。使用Java内置的网络功能来处理网络请求并不是很方便。 - coolguy