【发布时间】:2016-01-04 17:56:12
【问题描述】:
我想打开一个 URL 并向它提交以下参数,但它似乎只有在我将 BufferedReader 添加到我的代码时才有效。这是为什么呢?
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();
【问题讨论】:
-
如果您需要使用 HTTP,请考虑使用一些第三方库。
Apache HttpClient很不错。使用内置 Java 工具的网络不是很舒服
标签: java http httpurlconnection