Httpurlconction 与Servlet 之间相互传参
———-Httpurl:———-
public static void uploadFile(final Context context) {
new AsyncTask<String, Long, String>() {
protected void onPreExecute() {
View view = LayoutInflater.from(context).inflate(R.layout.dialog_upload_db_progress, null);
progressbar = (ProgressBar) view.findViewById(R.id.progressBar);
tv_uploadState = (TextView) view.findViewById(R.id.uploadState);
tv_uploadProgress = (TextView) view.findViewById(R.id.uploadProgress);
dialog = new Dialog(context, R.style.loadDialog);
dialog.setContentView(view);
dialog.setCancelable(false);
// 设置dialog的尺寸
WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int screenWidth = displayMetrics.widthPixels;
int screenHeight = displayMetrics.heightPixels;
params.width = screenWidth / 5 * 4;
params.height = screenHeight / 5;
dialog.getWindow().setAttributes(params);
// 设置progress初始的进度值
progressbar.setProgress(0);
progressbar.setMax(100);
tv_uploadState.setText("正在上传......");
tv_uploadProgress.setText("0%");
dialog.show();
};
@Override
protected String doInBackground(String... params) {
// 获得PAd 店员的信息和电源的id
mUserDao = DaoManager.getDao(UserDao.class, context);
User user;
String nickName = null;
long userId = 0;
try {
user = mUserDao.getData();
nickName = user.getNickName();
userId = user.getId();
} catch (SQLException e1) {
e1.printStackTrace();
}
File file = new File(FILE_NAME);
length = file.length();
FileInputStream fis = null;
OutputStream os = null;
HttpURLConnection connection = null;
InputStream inputStream = null;
ByteArrayOutputStream baos = null;
try {
URL url = new URL(urlString);
fis = new FileInputStream(file);
byte[] buff = new byte[1024];
int len = 0;
long startPosition = 0L;
int times = 0;
long progress = 0L;
while ((len = fis.read(buff)) != -1) {
// byte[] b = Arrays.copyOfRange(buff, 0, len);
// uploadToServlet(startPosition, b);
// startPosition += len;
if (times == 0) {
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setRequestProperty("startPosition", String.valueOf(startPosition));
connection.setRequestProperty("fileName", nickName + "_" + userId + "_" + PhoneUtil.getVersionName(context));
// connection.connect();
connection.setConnectTimeout(30000);
connection.setReadTimeout(60000 * 3);
os = connection.getOutputStream();
}
times++;
os.write(buff);
os.flush();
progress += len;
if (times == 1024 * 1 || progress == length) {// 每次长传1M
times = 0;
os.close();
if (connection.getResponseCode() == 200) {
// 获得服务端发来的响应
inputStream = connection.getInputStream();
baos = new ByteArrayOutputStream();
byte[] bMessage = new byte[1024];
int m = 0;
while ((m = inputStream.read(bMessage)) != -1) {
baos.write(bMessage, 0, m);
}
String message = new String(baos.toByteArray());
Log.i("AAAA", "==message:" + message);
inputStream.close();
baos.close();
if ("successful".equals(message)) {
publishProgress(progress);
} else {
// TODO:上传失败
uploadAgainDialog("上传失败,是否重新上传", context);
break;
}
}
}
startPosition += len;
}
fis.close();
} catch (IOException e) {
Log.i("AAAA", "=IOException=" + e.toString());
uploadAgainDialog("网络异常,上传失败,是否重新上传", context);
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (os != null) {
os.close();
}
if (baos != null) {
baos.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(Long... values) {
progressbar.setProgress((int) (values[0] * 100 / length));
tv_uploadProgress.setText((int) (values[0] * 100 / length) + "%");
if (values[0] == length) {
tv_uploadState.setText("上传完成");
}
}
protected void onPostExecute(String result) {
dialog.dismiss();
};
}.execute("");
}
public static void uploadAgainDialog(final String title, final Context context) {
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
View view = LayoutInflater.from(context).inflate(R.layout.dialog_upload_db, null);
Button btn_sure = (Button) view.findViewById(R.id.btn_sure_upload);
Button btn_cancle = (Button) view.findViewById(R.id.btn_cancle_upload);
TextView tv_title = (TextView) view.findViewById(R.id.dialogTitle);
tv_title.setText(title);
final Dialog dialog = new Dialog(context, R.style.loadDialog);
dialog.setContentView(view);
WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int screenWidth = displayMetrics.widthPixels;
int screenHeight = displayMetrics.heightPixels;
params.width = screenWidth / 5 * 4;
params.height = screenHeight / 5;
dialog.getWindow().setAttributes(params);
btn_cancle.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
btn_sure.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
BigFileUploadUtil.uploadFile(context);
dialog.dismiss();
}
});
dialog.show();
}
});
}
———-## Servlet端 ##———-
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
getDataOfBigFile(request, response);
}
private void getDataOfBigFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = request.getHeader("fileName");
String startPosition = request.getHeader("startPosition");
long mStartWrite = Long.parseLong(startPosition);
System.out.println(mStartWrite);
InputStream is = null;
RandomAccessFile mAccessFile = null;
PrintWriter pw = null;
try {
is = request.getInputStream();
File file = new File("F:/" + fileName);
// System.out.println(is.available());
byte[] b = new byte[1024 * 8];
int len = 0;
if (mStartWrite == 0L) {// 每次重新上传数据时,将文件的清空
if (file.exists()) {
file.delete();
System.out.println("delete");
}
}
mAccessFile = new RandomAccessFile(file, "rw");
mAccessFile.seek(mStartWrite);
while ((len = is.read(b)) > 0) {
// System.out.println(len);
mAccessFile.write(b, 0, len);
}
pw = response.getWriter();
pw.write("successful");
pw.flush();
} catch (Exception e) {
PrintWriter pw1 = null;
try {
pw1 = response.getWriter();
pw1.write("failure");
pw1.flush();
pw1.close();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if (pw1 != null) {
pw1.close();
}
}
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (mAccessFile != null) {
mAccessFile.close();
}
if (pw != null) {
pw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// System.out.println(startPosition + "完毕");
}