我正尝试使用Java将验证码提交给decaptcher.com。 Decaptcher并没有很好的解释如何使用他们的API,所以我想弄清楚如何使用HTTP POST请求来提交验证码。下面是示例代码,我从他们的网站有:如何发送图片作为多部分POST请求的一部分 - Java HtmlUnit
<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>
我应该发送POST请求一样,到Web服务器,并得到一个字符串返回给我。这是我尝试在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的值设置为File对象而不是指向captcha存储位置的String? (captcha.png是我想提交的图像的名称)。
请问我宣布KeyValuePair为: – Dylan 2010-08-03 01:57:18
//假装我创建 “captcha.png” File对象调用的文件 新KeyValuePair( “PICT” 文件, “PNG”, “UTF-8”) 用UTF-8编码PNG文件吗? – Dylan 2010-08-03 02:00:59
我添加了一个我认为应该可以工作的例子。我不确定utf-8字符集,也许你应该尝试一下。 – 2010-08-03 10:11:31