相关疑难解决方法(0)

如何使用java.net.URLConnection来触发和处理HTTP请求

java.net.URLConnection在这里经常询问使用情况,Oracle教程对此非常简洁.

该教程基本上只显示了如何触发GET请求并读取响应.它没有解释如何使用它来执行POST请求,设置请求标头,读取响应标头,处理cookie,提交HTML表单,上传文件等.

那么,我如何使用java.net.URLConnection触发和处理"高级"HTTP请求?

java http urlconnection httprequest httpurlconnection

1903
推荐指数
11
解决办法
100万
查看次数

如何在HttpURLConnection中发送PUT,DELETE HTTP请求?

我想知道是否可以将PUT,DELETE请求(实际上)发送java.net.HttpURLConnection到基于HTTP的URL.

我已经阅读了很多文章,描述了如何发送GET,POST,TRACE,OPTIONS请求,但我仍然没有找到任何成功执行PUT和DELETE请求的示例代码.

java put httpurlconnection http-delete

131
推荐指数
4
解决办法
25万
查看次数

Java URLConnection - 我什么时候需要使用connect()方法?

我有一个问题是要理解该类中connect()方法的含义URLConnection.在下面的代码中,如果我使用该connect()方法,如果我不使用它,我会得到相同的结果.

为什么(或何时)我需要使用它?

URL u = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();

conn.connect();//with or without it I have the same result

InputStream in = conn.getInputStream();
int b;
while ((b = in.read()) != -1) {
 System.out.write(b);
}
Run Code Online (Sandbox Code Playgroud)

java urlconnection connect httpurlconnection

32
推荐指数
2
解决办法
2万
查看次数

为什么 HttpURLConnection 不发送 HTTP 请求

我想打开一个 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();
Run Code Online (Sandbox Code Playgroud)

但这段代码确实有效:

        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())); …
Run Code Online (Sandbox Code Playgroud)

java http httpurlconnection

3
推荐指数
1
解决办法
2703
查看次数