我正在开发一个非常简单的 http 机器人。我正在使用
javax.net.ssl.HttpsURLConnection
类,我必须提出多个请求。
代码片段:
HttpURLConnection urlConnection =
(HttpURLConnection) new URL(url+"?"+firstParameters).openConnection();
urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
headerFields = urlConnection.getHeaderFields();
keys = headerFields.keySet();
for(String key : keys){
if(key != null && key.contains("ookie")){
cookies = urlConnection.getHeaderField(key);
break;
}
}
for(String cookie : cookies.split(";")){
if(cookie.contains("JSESSION")){
JSESSION = cookie.split("=")[1];
break;
}
}
document = new InputSource(urlConnection.getInputStream());
parser.setDocument(document);
attributesId.put("name",new ArrayList<String>(Arrays.asList(attributesNames)));
elementsIds.put("INPUT",attributesId);
elements = parser.getValues(elementsIds);
for(String attr : attributesNames){
secondParameters = secondParameters.replaceAll("#r"+index,elements.get(attr));
}
urlConnection.getInputStream().close();
//Second call
urlConnection = (HttpURLConnection) new URL(url2).openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Cookie", "JSESSIONID="+JSESSION);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
payload = new PrintWriter(urlConnection.getOutputStream());
payload.print(secondParameters);
payload.flush();
payload.close();
总结上面的代码,首先我执行一个没有任何有效负载的请求,并且我能够看到来自服务器的正确响应,但问题是当我发出第二个请求时(现在带有有效负载和 JSESSION cookie),我会做什么?收到的响应与我在第一个请求中收到的响应相同,看起来我正在再次发出第一个请求。 所以我的问题是,我做错了什么? 我只需要打开一个连接,然后更改标头和有效负载? 有没有与多个http请求(混合方法,post和get)相关的教程?
提前致谢
我以前从未使用过
HttpURLConnection
。我通常使用 Apache 的 HTTPClient 代码。他们的主页上有很多关于它的文档和教程。
我注意到你的代码的一些事情:
Cookie
标头。我的似乎处理得更好。JSESSION
吗?也许您还缺少其他饼干?JSESSION
cookie 得到正确设置?我在 cookie 处理代码中添加了一些 trim()
调用,以确保某些空格不会滑入其中。secondParameters
的真正价值。我不知道它们是否有效。您是否调试过代码以验证 secondParamters
值看起来不错。您可以在我的代码中看到我发布到服务器的内容。顺便说一句,我会使用 StringBuilder
而不是 +
来构建它们。希望这有帮助。