import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
public class FileUtil {
private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
/**
* 文件上传
*
* @param httpUrl 文件上传的url
* @param params 传递的参数
* @param headers
* @return
*/
@SuppressWarnings("finally")
public static byte[] downloadFile(String httpUrl, String params, Map<String, Object> headers) {
DataOutputStream ds = null;
BufferedInputStream in = null;
ByteArrayOutputStream bos = null;
try {
// 统一资源
URL url = new URL(httpUrl);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
// 设置是否从httpUrlConnection读入,默认情况下是true;
httpURLConnection.setDoInput(true);
// 设置是否向httpUrlConnection输出
httpURLConnection.setDoOutput(true);
// Post 请求不能使用缓存
httpURLConnection.setUseCaches(false);
// 设定请求的方法,默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置字符编码连接参数
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 设置请求内容类型
httpURLConnection.setRequestProperty("Content-Type", "application/json");
//设置header
httpURLConnection.setRequestProperty("X-CC-Key-ID", String.valueOf(headers.get("X-CC-Key-ID")));
httpURLConnection.setRequestProperty("X-CC-Auth-Key", String.valueOf(headers.get("X-CC-Auth-Key")));
// 设置DataOutputStream
ds = new DataOutputStream(httpURLConnection.getOutputStream());
//======传递参数======
ds.write(params.getBytes());
//======传递参数end======
ds.flush();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
bos = new ByteArrayOutputStream(10288);
in = new BufferedInputStream(httpURLConnection.getInputStream());
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len;
while (-1 != (len = in.read(buffer, 0, buf_size))) {
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} else {
throw new Exception(httpURLConnection.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ds != null) {
ds.close();
}
if (in != null) {
in.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
根据url下载文件字节码
最新推荐文章于 2024-09-03 20:17:53 发布