- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在这里经常问到java.net.URLConnection
的使用,而Oracle tutorial太简洁了。
该教程基本上仅显示如何触发GET请求并读取响应。它没有任何地方说明如何使用它来执行POST请求,设置请求标头,读取响应标头,处理cookie,提交HTML表单,上传文件等。
因此,如何使用java.net.URLConnection
触发和处理“高级” HTTP请求?
最佳答案
首先先声明一下:发布的代码段都是基本示例。您需要处理琐碎的IOException
和RuntimeException
(例如NullPointerException
,ArrayIndexOutOfBoundsException
)并自行整理。
准备中
我们首先至少需要知道URL和字符集。参数是可选的,并取决于功能要求。
String url = "http://example.com";
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String param1 = "value1";
String param2 = "value2";
// ...
String query = String.format("param1=%s¶m2=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
name=value
格式,并由
&
串联。通常,您还可以使用
URL-encode使用指定的字符集
URLEncoder#encode()
查询参数。
String#format()
只是为了方便起见。当我需要两次以上字符串连接运算符
+
时,我更喜欢它。
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...
?
连接到URL。
Accept-Charset
标头可能会提示服务器参数的编码方式。如果您不发送任何查询字符串,则可以不使用
Accept-Charset
标头。如果不需要设置任何标题,那么甚至可以使用
URL#openStream()
快捷方式。
InputStream response = new URL(url).openStream();
// ...
HttpServlet
,则将调用其
doGet()
方法,并且
HttpServletRequest#getParameter()
可以使用参数。
try (Scanner scanner = new Scanner(response)) {
String responseBody = scanner.useDelimiter("\\A").next();
System.out.println(responseBody);
}
URLConnection#setDoOutput()
设置为
true
会将请求方法隐式设置为POST。与Web表单一样,标准HTTP POST的类型为
application/x-www-form-urlencoded
,其中查询字符串被写入请求主体。
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes(charset));
}
InputStream response = connection.getInputStream();
// ...
name=value
元素的
<input type="hidden">
对放入查询字符串中,当然也将
name=value
元素的
<input type="submit">
对放入其中您希望以编程方式“按下”该按钮(因为通常在服务器端使用它来区分是否按下了按钮,如果按下了按钮,则区分是哪个按钮)。
URLConnection
强制转换为
HttpURLConnection
并使用其
HttpURLConnection#setRequestMethod()
。但是,如果您尝试将连接用于输出,则仍需要将
URLConnection#setDoOutput()
设置为
true
。
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.setRequestMethod("POST");
// ...
HttpServlet
,则将调用其
doPost()
方法,并且
HttpServletRequest#getParameter()
可以使用参数。
URLConnection#connect()
明确触发HTTP请求,但是当您想要获取有关HTTP响应的任何信息(例如使用
URLConnection#getInputStream()
的响应正文等)时,请求将自动按需触发。上面的示例正是这样做的,因此
connect()
调用实际上是多余的。
HttpURLConnection
。如有必要,请先进行投放。
int status = httpConnection.getResponseCode();
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
Content-Type
包含
charset
参数时,响应主体可能是基于文本的,那么我们希望使用服务器端指定的字符编码来处理响应主体。
String contentType = connection.getHeaderField("Content-Type");
String charset = null;
for (String param : contentType.replace(" ", "").split(";")) {
if (param.startsWith("charset=")) {
charset = param.split("=", 2)[1];
break;
}
}
if (charset != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
for (String line; (line = reader.readLine()) != null;) {
// ... System.out.println(line) ?
}
}
} else {
// It's likely binary content, use InputStream/OutputStream.
}
CookieHandler
API来维护cookie。发送所有HTTP请求之前,您需要为
CookieManager
和
CookiePolicy
设置
ACCEPT_ALL
。
// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
Set-Cookie
请求的响应中获取所有
GET
标头,然后将其传递给后续请求。
// Gather all cookies on the first request.
URLConnection connection = new URL(url).openConnection();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
// ...
// Then use the same cookies on all subsequent requests.
connection = new URL(url).openConnection();
for (String cookie : cookies) {
connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
// ...
split(";", 2)[0]
可以摆脱与服务器端无关的cookie属性,例如
expires
,
path
等。或者,也可以使用
cookie.substring(0, cookie.indexOf(';'))
代替
split()
。
HttpURLConnection
将在实际发送请求之前缓冲整个请求正文,无论您是否使用
connection.setRequestProperty("Content-Length", contentLength);
设置了固定的内容长度。每当您同时发送大型POST请求(例如上传文件)时,这可能会导致
OutOfMemoryException
。为避免这种情况,您想设置
HttpURLConnection#setFixedLengthStreamingMode()
。
httpConnection.setFixedLengthStreamingMode(contentLength);
HttpURLConnection#setChunkedStreamingMode()
来使用分块流式传输模式。这会将HTTP
Transfer-Encoding
标头设置为
chunked
,这将强制以块形式发送请求正文。以下示例将以1KB的块发送正文。
httpConnection.setChunkedStreamingMode(1024);
User-Agent
请求标头阻止请求。默认情况下,
URLConnection
将其设置为
Java/1.6.0_19
,其中最后一部分显然是JRE版本。您可以按如下方式覆盖它:
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7.
4nn
(客户端错误)或
5nn
(服务器错误),则您可能需要阅读
HttpURLConnection#getErrorStream()
以查看服务器是否发送了任何有用的错误信息。
InputStream error = ((HttpURLConnection) connection).getErrorStream();
HttpURLConnection
的实现是在较旧的JRE中实现连接保持活动状态存在一些漏洞。您可能需要通过将
http.keepAlive
系统属性设置为
false
将其关闭。您可以通过以下方式在应用程序的开头以编程方式执行此操作:
System.setProperty("http.keepAlive", "false");
multipart/form-data
编码。编码在
RFC2388中有更详细的描述。
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// Send normal param.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
// Send text file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
writer.append(CRLF).flush();
Files.copy(textFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// Send binary file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
}
HttpServlet
,则将调用其
doPost()
方法,并且
HttpServletRequest#getPart()
可以使用这些部件(请注意,因此不是
getParameter()
,依此类推!)。但是
getPart()
方法相对较新,它是在Servlet 3.0(Glassfish 3,Tomcat 7等)中引入的。在Servlet 3.0之前,您的最佳选择是使用
Apache Commons FileUpload解析
multipart/form-data
请求。有关FileUpload和Servelt 3.0方法的示例,另请参见
this answer。
javax.net.ssl.SSLException: Not trusted server certificate
,或者在某些配置错误的HTTPS站点上面临
java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found
或
javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name
。
static
初始化程序应使
HttpsURLConnection
对那些HTTPS站点更宽容,因此不再抛出这些异常。
static {
TrustManager[] trustAllCertificates = new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null; // Not relevant.
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// Do nothing. Just allow them all.
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// Do nothing. Just allow them all.
}
}
};
HostnameVerifier trustAllHostnames = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true; // Just allow them all.
}
};
try {
System.setProperty("jsse.enableSNIExtension", "false");
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCertificates, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
}
catch (GeneralSecurityException e) {
throw new ExceptionInInitializerError(e);
}
}
关于java - 如何使用java.net.URLConnection触发和处理HTTP请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56853460/
我正在尝试从该网站抓取历史天气数据: http://www.hko.gov.hk/cis/dailyExtract_uc.htm?y=2016&m=1 在阅读了 AJAX 调用后,我发现请求数据的正确
我有两个 postman 请求 x,y,它们命中了两个不同的休息 api X,Y 中的端点。 x 会给我一个身份验证 token ,这是发出 y 请求所必需的。如何在请求 y 中发出请求 x ?也就是
我使用请求库通过 API 与其他服务器进行通信。但现在我需要同时发送多个(10 个或更多)POST 请求,并且只有在所有响应都正确的情况下才能进一步前进。通常语法看起来有点像这样: var optio
背景:当用户单击按钮时,其类会在class1和class2之间切换,并且此数据是通过 AJAX 提交。为了确认此数据已保存,服务器使用 js 进行响应(更新按钮 HTML)。 问题:如果用户点击按钮的
我正在将 Node.js 中的请求库用于 Google 的文本转语音 API。我想打印出正在发送的请求,如 python example . 这是我的代码: const request = requi
我经常使用requests。最近我发现还有一个 requests2 和即将到来的 requests3 虽然有一个 page其中简要提到了 requests3 中的内容,我一直无法确定 requests
我正在尝试将图像发送到我的 API,然后从中获取结果。例如,我使用发送一个 bmp 图像文件 file = {"img": open("img.bmp)} r = requests.post(url,
我发现 Google Cloud 确保移出其物理环境的任何请求都经过强制加密,请参阅(虚拟机到虚拟机标题下的第 6 页)this link Azure(和 AWS)是否遵循类似的程序?如果有人能给我指
我有一个 ASP.NET MVC 应用程序,我正在尝试在 javascript 函数中使用 jQuery 来创建一系列操作。该函数由三部分组成。 我想做的是:如果满足某些条件,那么我想执行同步 jQu
我找不到如何执行 get http 请求,所以我希望你们能帮助我。 这个想法是从外部url(例如 https://api.twitter.com/1.1/search/tweets.json?q=tw
我的应用只需要使用“READ_SMS”权限。我的问题是,在 Android 6.0 上,当我需要使用新的权限系统时,它会要求用户“发送和查看短信”。 这是我的代码: ActivityCompat.re
我的前端代码: { this.searchInput = input; }}/> 搜索 // search method: const baseUrl = 'http://localho
我有一个由 AJAX 和 C# 应用程序使用的 WCF 服务, 我需要通过 HTTP 请求 header 发送一个参数。 在我的 AJAX 上,我添加了以下内容并且它有效: $.ajax({
我正在尝试了解如何使用 promises 编写代码。请检查我的代码。这样对吗? Node.js + 请求: request(url, function (error, response, body)
如果失败(除 HTTP 200 之外的任何响应代码),我需要重试发送 GWT RPC 请求。原因很复杂,所以我不会详细说明。到目前为止,我在同一个地方处理所有请求响应,如下所示: // We
当用户单击提交按钮时,我希望提交表单。然而,就在这种情况发生之前,我希望弹出一个窗口并让他们填写一些数据。一旦他们执行此操作并关闭该子窗口,我希望发出 POST 请求。 这可能吗?如果可能的话如何?我
像 Facebook 这样的网站使用“延迟”加载 js。当你必须考虑到我有一台服务器,流量很大时。 我很感兴趣 - 哪一个更好? 当我一次执行更多 HTTP 请求时 - 页面加载速度较慢(由于限制(一
Servlet 容器是否创建 ServletRequest 和 Response 对象或 Http 对象?如果是ServletRequest,谁在调用服务方法之前将其转换为HttpServletReq
这是维基百科文章的摘录: In contrast to the GET request method where only a URL and headers are sent to the serv
我有一个循环,每次循环时都会发出 HTTP post 请求。 for(let i = 1; i console.log("succes at " + i), error => con
我是一名优秀的程序员,十分优秀!