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();
}
}
}
java 模拟表单上传 httppost httpclient
米米羊的翅膀
10 years, 6 months ago
Answers
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
How can I make a multipart/form-data POST request using Java?
vobiz
answered 10 years, 6 months ago