Java 以多端口形式发送虚拟文件

Java 以多端口形式发送虚拟文件,java,Java,我想将文件内容作为org.apache.http.entity.mime.MultipartEntity发送。问题是,我没有真正的文件,只有String的内容。以下测试非常有效,其中file是指向有效png文件的java.io.file: MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("source", new StringBody("co

我想将文件内容作为
org.apache.http.entity.mime.MultipartEntity
发送。问题是,我没有真正的文件,只有
String
的内容。以下测试非常有效,其中
file
是指向有效png文件的
java.io.file

MultipartEntity entity = 
  new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("source", new StringBody("computer"));
entity.addPart("filename", new FileBody(file, "image/png"));
HttpPost httpPost = new HttpPost(URL);
httpPost.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();

final HttpResponse response = httpClient.execute(httpPost);
System.out.println(EntityUtils.toString(response.getEntity()));
稍后,我将没有一个真正的文件,而只有它的内容作为
String
。我对编码不太了解(更不用说什么了),但是如果我用同样的方法创建一个临时文件,它是以下面的方式创建的

String contents = FileUtils.readFileToString(new File(path),"UTF8");
File tmpFile = File.createTempFile("image", "png");
tmpFile.deleteOnExit();
InputStream in = new ByteArrayInputStream(contents.getBytes("UTF8"));
FileOutputStream out = new FileOutputStream(tmpFile);
org.apache.commons.io.IOUtils.copy(in, out);
路径指向与第一个代码块中成功的png文件完全相同的png文件,但这次我得到了一个

上传图像失败;不支持该格式


来自服务器的错误。我怀疑这和编码有关。有人知道我做错了什么吗?

不要使用readFileToString,而是readFileToByteArray,不要将内容存储在字符串中,而是存储在字节[]中:

byte[] contents = FileUtils.readFileToByteArray(new File(path));
File tmpFile = File.createTempFile("image", "png");
tmpFile.deleteOnExit();
InputStream in = new ByteArrayInputStream(contents);
FileOutputStream out = new FileOutputStream(tmpFile);
org.apache.commons.io.IOUtils.copy(in, out);

“内容”似乎是一个二进制文件,而不是可以转换为字符串的文件。我自己不会想到使用
String
,但在这种情况下,Mathematica和Java之间的接口有点不清楚。虽然我甚至可以用Mathematica中的
字符串
表示二进制内容,但当我将其发送到Java时,它就会出错。无论如何,将其转换为数字(字节)列表非常有效。