接口上传文件
作者:互联网
/**
* @param url 请求地址
* @param map 请求的参数
* @param body_data 上传的文件二进制内容
* @param fileName 文件路径
* @param charset 字符集
* @return
*/
public static String fileUpload(String url, Map<String, String> map,
byte[] body_data, String fileName, String charset) {
final String NEWLINE = "\r\n";
final String PREFIX = "--";
final String BOUNDARY = "#";
HttpURLConnection httpConn = null;
BufferedInputStream bis = null;
DataOutputStream dos = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
URL urlObj = new URL(url);
httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setUseCaches(false);
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
httpConn.setRequestProperty("Cache-Control", "no-cache");
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
httpConn.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)");
httpConn.connect();
dos = new DataOutputStream(httpConn.getOutputStream());
if (map != null && !map.isEmpty()) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = map.get(key);
dos.writeBytes(PREFIX + BOUNDARY + NEWLINE);
dos.writeBytes("Content-Disposition: form-data; "
+ "name=\"" + key + "\"" + NEWLINE);
dos.writeBytes(NEWLINE);
dos.writeBytes(URLEncoder.encode(value.toString(), charset));
dos.writeBytes(NEWLINE);
}
}
if (body_data != null && body_data.length > 0) {
dos.writeBytes(PREFIX + BOUNDARY + NEWLINE);
dos.writeBytes("Content-Disposition: form-data; " + "name=\""
+ "file" + "\"" + "; filename=\"" + fileName
+ "\"" + NEWLINE);
dos.writeBytes(NEWLINE);
dos.write(body_data);
dos.writeBytes(NEWLINE);
}
dos.writeBytes(PREFIX + BOUNDARY + PREFIX + NEWLINE);
dos.flush();
byte[] buffer = new byte[8 * 1024];
int c = 0;
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
}
return new String(baos.toByteArray(), charset);
} catch (HttpHostConnectException e) {
// 找不到服务,但IP通
throw new RpcException(ClientResCode.RC_HTTP_HTTPHOSTCONNECTEXCEPTION, e.getMessage());
} catch (UnknownHostException e) {
// IP错误
throw new RpcException(ClientResCode.RC_HTTP_UNKNOWNHOSTEXCEPTION, e.getMessage());
} catch (ConnectTimeoutException e) {
// IP不通,连接超时
throw new RpcException(ClientResCode.RC_CONNECT_TIMEOUT, e.getMessage());
} catch (SocketTimeoutException e) {
throw new RpcException(ClientResCode.RC_REQUEST_TIMEOUT, e.getMessage());
} catch (Exception e) {
throw new RpcException(ClientResCode.RC_OTHER_NETWORK_ERROR, e.getMessage());
} finally {
try {
if (dos != null) {
dos.close();
}
if (bis != null) {
bis.close();
}
if (baos != null) {
baos.close();
}
httpConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 文件上传接口
*
* @param url
* @param params
* @param rpcBaseReq
* @return
* @throws RpcException
* @throws Exception
*/
public String post(String url, String params) throws RpcException, Exception {
File file = new File(params);// params:pdf所在路径
byte[] bytes = File2byte(file);
FileInputStream fileInputStream = new FileInputStream(file);
// MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
// ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
String jsonResult = HttpUtil.fileUpload(url, new HashMap<>(),bytes,file.getName(),"utf-8");
// System.out.println(jsonResult);
return jsonResult;
}
/**
* 将文件转换成byte数组
* @param tradeFile
* @return
*/
public static byte[] File2byte(File tradeFile){
byte[] buffer = null;
try
{
FileInputStream fis = new FileInputStream(tradeFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1)
{
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return buffer;
}
标签:文件,writeBytes,String,NEWLINE,接口,httpConn,new,dos,上传 来源: https://blog.csdn.net/qq_40572200/article/details/121147775