1.远程下载url的二进制文件
//获取二进制文件
public static byte[] downLoadBinary(String urlStr) throws IOException{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为10秒
conn.setConnectTimeout(10*1000);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36");
//得到header
Map<String, List<String>> map = conn.getHeaderFields();
String fileName = map.get("Content-Disposition").get(0);
fileName = fileName.substring(fileName.indexOf("=") + 1);
System.out.println(fileName);
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取数据数组
byte[] getData = readInputStream(inputStream);
System.out.println(url + " download success");
return getData;
}
//输入流转二进制
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
2.上传二进制文件到远程url
public String sendBinary(byte[] bytes,String toUrl,String fileName){
PostMethod postMethod = new PostMethod(toUrl);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
try {
//FilePart用来上传文件的类,file即要上传的文件
//FilePart fp = new FilePart("file", file);
FilePart fp = new CustomFilePart("file",new ByteArrayPartSource(fileName,bytes));
//fp.setCharSet("UTF-8");
//普通参数orientation=true&oblique=true&x_tolerance=50&y_tolerance=20
StringPart orientation = new StringPart("orientation", "true");
StringPart oblique = new StringPart("oblique", "true");
StringPart x_tolerance = new StringPart("x_tolerance", "50");
StringPart y_tolerance = new StringPart("y_tolerance", "20");
Part[] parts = {fp,orientation,oblique,x_tolerance,y_tolerance};
//对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
postMethod.setRequestEntity(mre);
org.apache.commons.httpclient.HttpClient client = new HttpClient();
//由于要上传的文件可能比较大,因此在此设置最大的连接超时时间
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
//client.getParams().setContentCharset("UTF-8");
//client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
// 返回请求
int status = client.executeMethod(postMethod);
if (status == HttpStatus.SC_OK) {
log.info(toUrl + "发送成功" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
return postMethod.getResponseBodyAsString();
}else{
log.info("发送失败:" + status);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放连接
postMethod.releaseConnection();
}
return null;
}
//重写FilePart导致中文文件名乱码
public class CustomFilePart extends FilePart {
public CustomFilePart(String filename, File file)
throws FileNotFoundException {
super(filename, file);
}
public CustomFilePart(String name, PartSource partSource) {
super(name, (PartSource)partSource, (String)null, (String)null);
}
@Override
protected void sendDispositionHeader(OutputStream out) throws IOException {
super.sendDispositionHeader(out);
String filename = getSource().getFileName();
if (filename != null) {
out.write(org.apache.commons.httpclient.util.EncodingUtil.getAsciiBytes(FILE_NAME));
out.write(QUOTE_BYTES);
//重写编码
out.write(EncodingUtil.getBytes(filename, "utf-8"));
out.write(QUOTE_BYTES);
}
}
}
3.依赖的httpclient
<!--httpclient-->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
1.远程下载url的文件
public static void downLoadFromUrl(String urlStr, String savePath) throws IOException{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为10秒
conn.setConnectTimeout(10*1000);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36");
//得到返回的header
Map<String, List<String>> map = conn.getHeaderFields();
System.out.println(map);
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] getData = readInputStream(inputStream);
//文件保存位置
File saveDir = new File(savePath);
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+File.separator+fileName);
FileOutputStream fos = new FileOutputStream(file);
//写入文件
fos.write(getData);
if(fos!=null){
fos.close();
}
if(inputStream!=null){
inputStream.close();
}
System.out.println(url+" 下载成功");
2.上传文件
public static void sendFile(String url, File file) {
if (StringUtils.isBlank(url)) {
throw new RuntimeException("url为空");
}
if (!file.exists()) {
throw new RuntimeException("文件不存在");
}
PostMethod postMethod = new PostMethod(url);
BufferedReader br = null;
try {
//FilePart:用来上传文件的类,file即要上传的文件
FilePart fp = new CustomFilePart("file", file);
Part[] parts = {fp};
//对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
postMethod.setRequestEntity(mre);
HttpClient client = new HttpClient();
//超时时间
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
int status = client.executeMethod(postMethod);
if (status == HttpStatus.SC_OK) {
/*InputStream inputStream = postMethod.getResponseBodyAsStream();
br = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}*/
System.out.println("发送成功");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 释放连接
postMethod.releaseConnection();
}
3.依赖的httpclient
<!--httpclient-->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>