public static String mapToTxt(Map<String,String> fieldMap, Map<String,File> fileMap,String fileName) throws Exception{
Random random = new Random();
int j;
String getLine = "\r\n";
String fileType = "Content-Type: application/octet-stream";
String doubleBar = "--";
biaoshi = "----WebKitFormBoundary";
StringBuffer sb = new StringBuffer();
for(int i = 0; i < 16;i++){
j = random.nextInt(MULTIPART_CHARS.length-2)+2;
sb.append(MULTIPART_CHARS[j]);
}
biaoshi = biaoshi + sb.toString();
StringBuffer stringBuffer = new StringBuffer();
for (Map.Entry<String,String> entity:fieldMap.entrySet()) {
String name = "Content-Disposition: form-data; name=\""+entity.getKey()+"\"";
stringBuffer.append(doubleBar+biaoshi);
stringBuffer.append(getLine);
stringBuffer.append(name);
stringBuffer.append(getLine);
stringBuffer.append(getLine);
stringBuffer.append(entity.getValue());
stringBuffer.append(getLine);
}
for (Map.Entry<String,File> entity:fileMap.entrySet()) {
String name = "Content-Disposition: form-data; name=\""+fileName+"\"; filename=\""+entity.getValue().getName()+"\"";
stringBuffer.append(doubleBar+biaoshi);
stringBuffer.append(getLine);
stringBuffer.append(name);
stringBuffer.append(getLine);
stringBuffer.append(fileType);
stringBuffer.append(getLine);
stringBuffer.append(getLine);
File f = entity.getValue();
FileInputStream fileInputStream = new FileInputStream(f);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte by[] = new byte[1024];
int k = 0;
while ((k=fileInputStream.read(by))!=-1){
byteArrayOutputStream.write(by,0,k);
}
by = byteArrayOutputStream.toByteArray();
for(int i = 0; i < by.length; i++){
stringBuffer.append(by[i]);
}
stringBuffer.append(getLine);
}
stringBuffer.append(doubleBar+biaoshi+doubleBar);
return stringBuffer.toString();
}
java map转Multipart/form-data类型body
最新推荐文章于 2024-08-25 02:37:20 发布