想做个上传文件的负载均衡,但是HttpURLConnection没有端口号,传输的文件会找不到地址。
遥了老命 2017-09-12 11:23:35 举例说明下问题:
一个 5g的文件, 循环第一次,传输了100m,收到返回消息,再第二次传输100m,直到完成。
如果url写上端口,实现这个,下面代码没有问题。
如果不写端口,第一次的 100m ,服务端接收到了。第二次以后就不知道传到哪里了。
这个怎么解决?
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 问题:传一个5g的文件。
* 如果 url里写端口号,没有问题。
* 如果不写端口号,则会出现问题: 分段传输,第一次可以找到,第二次以后就找不到里,不知道传到哪里里。
*/
public class TestUpload {
public void run() {
HttpURLConnection connection = null;
OutputStream outputStream = null;
RandomAccessFile randomAccessFile = null;
Boolean canSend = true;// 判断是否需要继续传输。
long uploadLen = 0;// 已经上传的大小。
File f = new File("11.exe");
while (canSend) {
try {
// a、确实文件上传位置
randomAccessFile = new RandomAccessFile(f, "r");
// b、创建连接对象(设置当前文件信息标识)
randomAccessFile.seek(uploadLen);
// 文件大小 - 已经上传大小 > 100MB ,如果true,就再次传100mb,否则传剩下大小。
long remanentSize = randomAccessFile.length() - uploadLen;
int rate = 1024 * 1024 * Content.UPLOAD_SIZE;
int fixedSize = (int) (remanentSize < rate ? remanentSize : rate);
if (fixedSize <= 0) {
System.out.println("------->> 文件 " + f.getName() + " 上传出错。");
System.out.println("------->> 文件已经上传:" + uploadLen + "。");
System.out.println("------->> 文件客户端实际大小:" + randomAccessFile.length() + "。");
return;
}
HttpURLConnection conn = null;
URL url = null;
String urls = null;
try {
url = new URL("http://127.0.0.1:8081/upload.do");
conn = (HttpURLConnection) url.openConnection();
// 设置上传方式:以流的方式发送,而非写入缓存然后发送(引起heep out),这种方式不写入内容,每次传的流比较大
// 备注:但必须指定发送的流的大小,如果超出或小于会出异常
conn.setFixedLengthStreamingMode(f.length());
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-type", "application/x-java-serialized-object");
conn.setDefaultUseCaches(false);
conn.setRequestMethod("POST");
conn.setConnectTimeout(30 * 1000);
conn.setReadTimeout(30 * 1000);
} catch (IOException e) {
e.printStackTrace();
}
// c、打开输出流,并写入数据
outputStream = connection.getOutputStream();
int readBuffer = 1024 * 1024 * 2;
byte[] buf = new byte[readBuffer];
int readLength = 0;
while ((readLength = randomAccessFile.read(buf)) != -1 ) {
// System.out.println("while读取的长度: " + readLength);
outputStream.write(buf, 0, readLength);
}
uploadLen += fixedSize;
// System.out.println("------->> uploadLen的长度: " + uploadLen);
// outputStream.flush();
outputStream.close();
randomAccessFile.close();
} catch (Exception e) {
e.printStackTrace();
}
// 接收返回值.
canSend = Boolean.parseBoolean(connection.getHeaderField("canSend"));
}
}
}