我试图获取页面(HTML),从中读取特殊令牌(每次都不同),然后发送POST请求,但这会给我java.lang.IllegalStateException: connect in progress
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中获取此令牌,那么同样如此:
final String token=con.getHeaderField("Set-Cookie").replace("__Token=", "").replace("; path=/; HttpOnly", "");
如何正确地做到这一点?
答案 0 :(得分:6)
documentation of HttpURLConnection
说:
每个HttpURLConnection实例用于发出单个请求 与HTTP服务器的底层网络连接可能是 由其他实例透明地共享。
这意味着您无法在同一HttpURLConnection
对象上创建新的(POST)请求。事实上,你从中获得IllegalStateException
。
因此,您应该从final
的定义中删除con
修饰符,然后在完成处理原始(GET)请求的输出后,创建另一个连接:
con = (HttpURLConnection) url.openConnection();
只有这样,您才能继续构建POST请求。
注意:您使用try-with-resources,因此您无需显式关闭流。此外,您不需要两个try
块。实际上,您无需保留对InputStreamReader
的引用,因为BufferedReader.close()
也会关闭基础Reader
,这也会关闭基础InputStream
。