我尝试获取页面(HTML),从中读取特殊 token (每次都不同),然后发送 POST 请求,但这给了我java.lang.IllegalStateException:连接正在进行中
final URL url = new URL("<...>");
String token = null;
final HttpURLConnection con = (HttpURLConnection) url.openConnection();
try (final InputStreamReader isr = new InputStreamReader(con.getInputStream())) {
try (final BufferedReader in = new BufferedReader(isr)) {
String str;
while ((str = in.readLine()) != null) {
if (str.contains("__token")) {
token = str.replace("<...>", "").replace("<...>", "");
System.out.println(token);
break;
}
}
in.close();
}
isr.close();
}
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setDoOutput(true);
try (final DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
final String params = getParams("par1", "par2", token);
wr.writeBytes(params);
wr.flush(); wr.close();
final int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + params);
System.out.println("Response Code : " + responseCode);
try (final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
String inputLine;
final StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
如果我尝试从 cookie 获取此 token ,情况也是如此:
final String token=con.getHeaderField("Set-Cookie").replace("__Token=", "").replace("; path=/; HttpOnly", "");
如何正确地做到这一点?
最佳答案
documentation of HttpURLConnection
说:
Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances.
这意味着您无法在同一个 HttpURLConnection
对象上创建新的 (POST) 请求。事实上,您会从中得到一个 IllegalStateException
。
因此,您应该从 con
的定义中删除 final
修饰符,然后在完成原始 (GET) 请求的输出处理后,创建另一个连接:
con = (HttpURLConnection) url.openConnection();
只有这样,您才能继续构建 POST 请求。
<小时/>一点注意:您使用 try-with-resources,因此不需要显式关闭流。此外,您不需要两个 try
block 。事实上,您不需要保留对 InputStreamReader
的引用,因为 BufferedReader.close()
还会关闭底层 Reader
,这还关闭底层的InputStream
。
关于java - HttpURLConnection getInputStream读取页面,然后发出POST请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27571645/