我正在尝试使用 Java 向 decaptcher.com 提交验证码。 Decaptcher 并没有很好地解释如何使用他们的 API,所以我试图弄清楚如何使用 HTTP POST 请求来提交验证码。这是我从他们的网站上获得的示例代码:
<form
method="post"
action="http://poster.decaptcher.com/"
enctype="multipart/form-data">
<input type="hidden" name="function" value="picture2">
<input type="text" name="username" value="client">
<input type="text" name="password" value="qwerty">
<input type="file" name="pict">
<input type="text" name="pict_to" value="0">
<input type="text" name="pict_type" value="0">
<input type="submit" value="Send">
</form>
我应该向网络服务器发送一个类似的发布请求,并得到一个返回给我的字符串。这是我用 Java 实现它的尝试。
public String getDecaptcherAnswer(String username, String password){
try{
URL decaptcherPostURL = new URL("http://poster.decaptcher.com/");
WebRequestSettings request = new WebRequestSettings(decaptcherPostURL, HttpMethod.POST);
request.setEncodingType(FormEncodingType.MULTIPART);
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new NameValuePair("function", "picture2"));
params.add(new NameValuePair("username", username));
params.add(new NameValuePair("password", password));
//I added this block in
File file = new File("captcha.png");
params.add(new KeyDataPair("pict", capFile, "png", "utf-8"));
//----------------------
params.add(new NameValuePair("pict_to", "0"));
params.add(new NameValuePair("pict_type", "0"));
request.setRequestParameters(params);
request.setUrl(decaptcherPostURL);
HtmlPage page = webClient.getPage(request);
System.out.println(page.asText());
System.out.println("--------------------------------------");
System.out.println(page.asXml());
return page.asText();
}catch (Exception e){
e.printStackTrace();
return null;
}
}
我是否应该将 pict 的值设置为一个文件对象而不是指向验证码存储位置的字符串? (captcha.png 是我要提交的图片的名称)。
最佳答案
有一个更高级别的机制来发送该文件,您不需要创建 WebRequestSettings
并设置其单独的值。
您应该在某处托管该静态 html 并执行如下操作。
如果您仍有问题,请在 HtmlUnit 错误跟踪器中提交错误报告。
顺便说一句,HtmlUnit 2.8 即将发布,试试吧。
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage("http://some_host/test.html");
HtmlForm form = page.getForms().get(0);
form.getInputByName("username").setValueAttribute(username);
form.getInputByName("password").setValueAttribute(password);
form.getInputByName("pict_to").setValueAttribute("0");
form.getInputByName("pict_type").setValueAttribute("0");
form.getInputByName("pict").setValueAttribute("full_path_to_captcha_png");
form.<HtmlFileInput>getInputByName("pict").setContentType("image/png");//optional
HtmlPage page2 = form.getInputByValue("Send").click();
关于java - 如何将图片作为多部分 POST 请求的一部分发送 - Java HtmlUnit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3383473/