我想编写Java代码做的正是这个命令的作用:相当于Java用图片和文字卷曲POST请求的
curl -F "[email protected]" -F "param1=some-value" -F "param2=some_value" http://example.com
我目前想是这样的:
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost poster = new HttpPost("http://example.com");
MultipartEntityBuilder mpEntityBuilder = MultipartEntityBuilder.create();
mpEntityBuilder.addPart("param1", new StringBody("some-value"));
mpEntityBuilder.addPart("param2", new StringBody("some-value"));
mpEntity.addPart("image", getImage("some-image"));
poster.setEntity(mpEntityBuilder .build());
HttpResponse response = httpClient.execute(poster);
here getImage(String)返回一个ByteArrayBody。 (实际上,我从下载的飞行网路上的图片,而不是像从curl命令磁盘读取,但我不认为这应该有所作为)
我检查了这个链接,但它不”牛逼确切地址在你发送两个图像以及文本参数的情况: Java Equivalent of curl query
什么奇怪的是,我使用几乎相同的代码,使一个HTTP POST来时,我需要工作正常另一个API单独发送图像而没有任何文本参数。 (无stringbody)
但是,当我试图同时发送的图像(作为ByteArrayBody)和一些文字(如StringBody),我从服务器获取说像一个神秘的错误消息: “无法使用mimeType初始化参数对象:application/octet-stream'。这可能是一个自定义的错误信息,所以我不能在这方面找到很多信息。
我尝试使用StringBody()的一些其他构造函数,因为这个不推荐使用,但它没有帮助。不知道什么是正确的构造函数使用,但不知道这是否会导致问题。
编辑:好像某人的问过一个非常类似的问题,但解决方案并不为我工作: Android: upload file with filling out POST body together 我得到一个错误信息有关 失败参数初始化与mime类型:应用程序/八位字节流)
我相信你会需要Base64对图像进行编码。看看http://stackoverflow.com/questions/5416038/uploading-image-to-server-in-multipart-along-with-json-data-in-android – GreyBeardedGeek
谢谢,我会检查出来。但是这并不能解释为什么上面的代码可以很好地执行这个curl命令: curl -F“file”=“@ example.png”“https://example.com” – kerouac