httpclient - JAVA模拟表单上传遇到问题
PHPz
PHPz 2017-04-17 11:34:22
[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();  
    }  
}  

}

PHPz
PHPz

学习是最好的投资!

全部回复(1)
PHP中文网
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?

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号