JAVA模拟表单上传遇到问题
RT,我想向GOOGLE识图 上传一张图片并得到传回的地址,但是执行后,我得到回传的地址在浏览器打开,提示:无法按图搜索。
PS:我用Fiddler模拟提交了一次,是可以的,Fiddler的截图如下。 JAVA代码附在后边。还请指教,谢谢!
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
postFile();
}
private static void postFile() {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.google.com.tw/searchbyimage/upload");
try {
// 需要上传的文件
String root = "C:/";
String fileName = "AA.jpg";
File uploadFile = new File(root+fileName);
//定义FileEntity对象
HttpEntity entity = new FileEntity(uploadFile, "image/jpeg");
httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
String BOUNDARY = "----------" + System.currentTimeMillis();
httpPost.setHeader("Content-Type", "multipart/form-data; boundary="
+ BOUNDARY);
httpPost.setEntity(entity); //设置实体对象
// httpClient执行httpPost提交
HttpResponse response = httpClient.execute(httpPost);
// 得到服务器响应实体对象
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
System.out.println(EntityUtils.toString(responseEntity, "utf-8"));
System.out.println("文件 "+fileName+"上传成功!");
} else {
System.out.println("服务器无响应!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
httpClient.getConnectionManager().shutdown();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
How can I make a multipart/form-data POST request using Java?