关于这个获取流转换成文件,乱码问题,我们始终无法避免。
奉上正确方法
/**
* 向server端发送请求,并获取返回参数
* @param actionUrl
* @param param
* @return
*/
public static byte[] sendPostRequest(String serverUrl,String param) {
logger.debug("+++++++++++++++sendPostRequest方法开始!+++++++++++++++++++");
StringBuffer sb = new StringBuffer();
String output = "";
try {
URL url = new URL(serverUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
if (param != null) {
OutputStream os = conn.getOutputStream();
os.write(param.getBytes("utf-8"));
os.flush();
}
InputStream is = conn.getInputStream();
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int rc;
while ((rc = is.read(buff, 0, 1024)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
conn.disconnect();
return in2b;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
注意,这里一定要用ByteArrayOutputStream 不要用BufferedReader
上面获取到流,下面将流转换成文件
/**
* 将Byte数组转换成文件
* @param bytes
* @param filePath
* @param fileName
*/
public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
filePath = filePath + "\\forUpload";
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath + "\\" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}