关于消息的使用,下面的博客讲的比较详细。
https://www.cnblogs.com/Quejamais/p/5650666.html
package com.common; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.UUID; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log; public class UploadUtil1 { private Handler myHandle; private static UploadUtil1 uploadUtil; private static final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 private static final String PREFIX = "--"; private static final String LINE_END = "\r\n"; private static final String CONTENT_TYPE = "multipart/form-data"; // 内容类型 private UploadUtil1() { } /** * 单例模式获取上传工具类 * @return */ public static UploadUtil1 getInstance() { if (null == uploadUtil) { uploadUtil = new UploadUtil1(); } return uploadUtil; } private static final String TAG = "UploadUtil"; private int readTimeOut = 10 * 1000; // 读取超时 private int connectTimeout = 10 * 1000; // 超时时间 /*** * 请求使用多长时间 */ private static int requestTime = 0; private static final String CHARSET = "utf-8"; // 设置编码 /*** * 上传成功 */ public static final int UPLOAD_SUCCESS_CODE = 1; /** * 文件不存在 */ public static final int UPLOAD_FILE_NOT_EXISTS_CODE = 2; /** * 服务器出错 */ public static final int UPLOAD_SERVER_ERROR_CODE = 3; protected static final int WHAT_TO_UPLOAD = 1; protected static final int WHAT_UPLOAD_DONE = 2; /** * android上传文件到服务器 * * @param filePath * 需要上传的文件的路径 * @param fileKey * 在网页上 xxx就是这里的fileKey * @param RequestURL * 请求的URL */ public void uploadFile(String filePath, String fileKey, String RequestURL, Map, String> param) { if (filePath == null) { sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在"); return; } try { File file = new File(filePath); uploadFile(file, fileKey, RequestURL, param); } catch (Exception e) { sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在"); e.printStackTrace(); return; } } /** * android上传文件到服务器 * * @param file * 需要上传的文件 * @param fileKey * 在网页上 xxx就是这里的fileKey * @param RequestURL * 请求的URL */ public void uploadFile(final File file, final String fileKey, final String RequestURL, final Map , String> param) { if (file == null || (!file.exists())) { sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在"); return; } Log.i(TAG, "请求的URL=" + RequestURL); Log.i(TAG, "请求的fileName=" + file.getName()); Log.i(TAG, "请求的fileKey=" + fileKey); new Thread(new Runnable() { //开启线程上传文件 @Override public void run() { toUploadFile(file, fileKey, RequestURL, param); } }).start(); } private void toUploadFile(File file, String fileKey, String RequestURL, Map , String> param) { String result = null; requestTime= 0; long requestTime = System.currentTimeMillis(); long responseTime = 0; try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(readTimeOut); conn.setConnectTimeout(connectTimeout); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); // conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); //conn.setRequestProperty("ENCTYPE", "multipart/form-data"); // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); /** * 当文件不为空,把文件包装并且上传 */ DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); StringBuffer sb = null; String params = ""; /*** * 以下是用于上传参数 */ if (param != null && param.size() > 0) { Iterator it = param.keySet().iterator() ; while (it.hasNext()) { sb = null; sb = new StringBuffer(); String key = it.next(); String value = param.get(key); sb.append(PREFIX).append(BOUNDARY).append(LINE_END); sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END); sb.append(value).append(LINE_END); params = sb.toString(); Log.i(TAG, key+"="+params+"##"); dos.write(params.getBytes()); // dos.flush(); } } sb = null; params = null; sb = new StringBuffer(); /** * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append(PREFIX).append(BOUNDARY).append(LINE_END); sb.append("Content-Disposition:form-data; name=\"" + fileKey + "\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type:image/jpeg" + LINE_END); // 这里配置的Content-type很重要的 ,用于服务器端辨别文件的类型的 // sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END); sb.append(LINE_END); params = sb.toString(); Log.d(TAG, "toUploadFile: ************----------------------->>> "+params); sb = null; Log.i(TAG, file.getName()+"=" + params+"##"); dos.write(params.getBytes()); /**上传文件*/ InputStream is = new FileInputStream(file); // onUploadProcessListener.initUpload((int)file.length()); byte[] bytes = new byte[1024]; int len = 0; int curLen = 0; while ((len = is.read(bytes)) != -1) { curLen += len; dos.write(bytes, 0, len); // onUploadProcessListener.onUploadProcess(curLen); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); dos.write(end_data); dos.flush(); // // dos.write(tempOutputStream.toByteArray()); /** * 获取响应码 200=成功 当响应成功,获取响应的流 */ Log.d(TAG, "toUploadFile: method "+conn.getRequestMethod()); int res = conn.getResponseCode(); responseTime = System.currentTimeMillis(); this.requestTime = (int) ((responseTime-requestTime)/1000); Log.e(TAG, "response code:" + res); if (res == 200) { Log.e(TAG, "request success"); InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.e(TAG, "result : " + result); Message msg=new Message(); msg.arg1=0; msg.arg2=2; msg.what=3; // msg.obj= myHandle.sendMessage(msg); sendMessage(UPLOAD_SUCCESS_CODE, "上传结果:" + result); return; } else { Log.e(TAG, "request error"); Message msg=new Message(); msg.arg1=1; msg.arg2=2; msg.what=3; // msg.obj= myHandle.sendMessage(msg); sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:code=" + res); return; } } catch (MalformedURLException e) { sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:error=" + e.getMessage()); e.printStackTrace(); return; } catch (IOException e) { sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:error=" + e.getMessage()); e.printStackTrace(); return; } } public void SetHandle(Handler handler){ myHandle = handler; } /** * 发送上传结果 * @param responseCode * @param responseMessage */ private void sendMessage(int responseCode,String responseMessage) { // onUploadProcessListener.onUploadDone(responseCode, responseMessage); } /** * 下面是一个自定义的回调函数,用到回调上传文件是否完成 * * @author shimingzheng * */ public static interface OnUploadProcessListener { /** * 上传响应 * @param responseCode * @param message */ void onUploadDone(int responseCode, String message); /** * 上传中 * @param uploadSize */ void onUploadProcess(int uploadSize); /** * 准备上传 * @param fileSize */ void initUpload(int fileSize); } private OnUploadProcessListener onUploadProcessListener; public void setOnUploadProcessListener( OnUploadProcessListener onUploadProcessListener) { this.onUploadProcessListener = onUploadProcessListener; } public int getReadTimeOut() { return readTimeOut; } public void setReadTimeOut(int readTimeOut) { this.readTimeOut = readTimeOut; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } /** * 获取上传使用的时间 * @return */ public static int getRequestTime() { return requestTime; } public static interface uploadProcessListener{ } public void doFileUpload(String urlString,String existingFileName,String keyStr) { HttpURLConnection conn = null; //DataOutputStream dos = null; DataInputStream inStream = null; //String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mypic.png"; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; // String urlString = "http://mywebsite.com/directory/upload.php"; Log.d(TAG, "doFileUpload: urlString:"+urlString+" existingFileName:"+existingFileName); try { //------------------ CLIENT REQUEST FileInputStream fileInputStream = new FileInputStream(new File(existingFileName)); // open a URL connection to the Servlet URL url = new URL(urlString); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod("POST"); conn.setRequestProperty("Charset", "utf-8"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); // dos = new DataOutputStream(conn.getOutputStream()); Log.d(TAG, "doFileUpload: ******** 1"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); Log.d(TAG, "doFileUpload: ******** 2"); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + existingFileName + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // close streams Log.e("Debug", "File is written"); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { Log.e("Debug", "error: " + ex.getMessage(), ex); } catch (IOException ioe) { Log.e("Debug", "error: " + ioe.getMessage(), ioe); } //------------------ read the SERVER RESPONSE try { inStream = new DataInputStream(conn.getInputStream()); String str; while ((str = inStream.readLine()) != null) { Log.e("Debug", "Server Response " + str); } inStream.close(); } catch (IOException ioex) { Log.e("Debug", "error: " + ioex.getMessage(), ioex); } } }
uploadUtil.SetHandle(handler); //用来设置消息
package com.example.suzyulin.emergency; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.common.AppData; import com.common.UploadUtil1; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; public class UploadFileActivity extends AppCompatActivity { private static final String TAG = "UploadFileActivity"; ImageView imageViewResult ; TextView tvUploadStatus; Button btnReturn; // handler对象,用来接收消息~ private Handler handler = new Handler() { @Override public void handleMessage(android.os.Message msg) { //这个是发送过来的消息 // 处理从子线程发送过来的消息 int arg1 = msg.arg1; //获取消息携带的属性值 int arg2 = msg.arg2; int what = msg.what; // Object result = msg.obj; // Log.d(TAG, "handleMessage: "+result); System.out.println("-arg1--->>" + arg1); System.out.println("-arg2--->>" + arg2); System.out.println("-what--->>" + what); Bundle bundle = msg.getData(); // 用来获取消息里面的bundle数据 // System.out.println("-getData--->>" // + bundle.getStringArray("strs").length); // btnReturn.setEnabled(true); switch (arg1){ case 0: tvUploadStatus.setText("Upload OK"); tvUploadStatus.setTextColor(Color.rgb(0, 255, 0)); handlerUpdateUI.removeMessages(0); // tvUploadStatus.setText("Upload OK"); //PhotoResult.setImageBitmap(FlexBitmap); break; case 1: tvUploadStatus.setText("Upload Fail"); tvUploadStatus.setTextColor(Color.rgb(255, 0, 0)); handlerUpdateUI.removeMessages(0); //tvUploadStatus.setText("Upload Fail"); break; } }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_upload_file); Log.d(TAG, "onCreate: delay 获取图片文件名 :"+AppData.getPhotoFileName(this)); imageViewResult = (ImageView)findViewById(R.id.ivCameraResult); btnReturn = (Button)findViewById(R.id.btnReturn); tvUploadStatus = (TextView)findViewById(R.id.tvUploadStatus); } public void onClick(View view) { System.out.println("onClick按钮被点击*********************!"); Intent intent = null; switch (view.getId()){ case R.id.btnReturn: try {
UploadFile();
}
catch (Exception e) { Log.
d(
TAG
,
"onClick: ButtonCamera Erro "+e.getMessage())
;
}
break;
default:
break;
} }
public static Bitmap
getLoacalBitmap(String url) {
try { FileInputStream fis =
new FileInputStream(url)
;
return BitmapFactory.
decodeStream(fis)
;
}
catch (FileNotFoundException e) { e.printStackTrace()
;
Log.
d(
TAG
,
"getLoacalBitmap: ---------> "+e.getMessage())
;
return null;
} }
private void
UploadFile(){ System.
out.println(
"用户点击了上传按钮")
;
String PhotoFileName = AppData.
getPhotoFileName(
this)
;
String UploadAddress = AppData.
getUploadAddress(
this)
;
String DoorID = AppData.
getBarcode(
this)
;
String doorStatus = AppData.
getDoorStauts(
this)
;
File file =
new File(PhotoFileName)
;
String fileKey =
"file"
;
UploadUtil1 uploadUtil = UploadUtil1.
getInstance()
;
uploadUtil.SetHandle(
handler)
;
Map