习惯了okhttp和 retrofit的银。回退版本去使用HttpURLConnection,真的感觉凉凉
package com.senseplay.ssp.ota.upload;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.senseplay.mframe.tool.MUtilTool;
import com.senseplay.ssp.http.HttpUrls;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class UploadTask {
private final static String BOUNDARY = UUID.randomUUID().toString()
.toLowerCase().replaceAll("-", "");// 边界标识
private final static String PREFIX = "--";// 必须存在
private final static String LINE_END = "\r\n";
private static final String TAG = "UploadTask";
public UploadTask() {
}
public static String uploadPic(File file, HashMap<String, String> paramsMap) {
Log.i(TAG, "uploadPic: ------开始上传"+file.length());
HttpURLConnection conn = null;
OutputStream os = null;
BufferedReader br = null;
String result=null;
try {
String httpUrl = "http://192.168.93.113:8044/diary/user/upload";
URL url = new URL(httpUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(1000 * 10);
conn.setReadTimeout(1000 * 10);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
conn.connect();
// 往服务器端写内容 也就是发起http请求需要带的参数
os = new DataOutputStream(conn.getOutputStream());
// 请求参数部分
// if (paramsMap != null && paramsMap.size() > 0) {
// String params = getParams(paramsMap, 1);
// byte[] postData = params.getBytes();
// os.write(postData);
// }
// 请求参数部分
writeParams(paramsMap, os);
Log.i(TAG, "上传文件: **********************************************************************************");
// 请求上传文件部分
writeFile(file, os);
// 请求结束标志
String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END;
os.write(endTarget.getBytes());
os.flush();
if (conn.getResponseCode() == 200) {
result = MUtilTool.streamToString(conn.getInputStream());
Log.i(TAG, "uploadPic: ----------result:" + result);
} else {
Log.e(TAG, "Post Error " + conn.getResponseCode());
}
return result;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.disconnect();
conn = null;
}
if (os != null) {
os.close();
os = null;
}
if (br != null) {
br.close();
br = null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return null;
}
private static void writeParams(HashMap<String, String> paramsMap, OutputStream os) {
try{
String msg = "请求参数部分:\n";
if (paramsMap == null || paramsMap.isEmpty()) {
msg += "空";
} else {
StringBuilder requestParams = new StringBuilder();
Set<Map.Entry<String, String>> set = paramsMap.entrySet();
Iterator<Map.Entry<String, String>> it = set.iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
requestParams.append("Content-Disposition: form-data; name=\"")
.append(entry.getKey()).append("\"").append(LINE_END);
requestParams.append("Content-Type: text/plain; charset=utf-8")
.append(LINE_END);
requestParams.append("Content-Transfer-Encoding: 8bit").append(
LINE_END);
requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容
requestParams.append(entry.getValue());
requestParams.append(LINE_END);
}
os.write(requestParams.toString().getBytes());
os.flush();
msg += requestParams.toString();
}
System.out.println(msg);
}catch(Exception e){
e.printStackTrace();
}
}
private static void writeFile(File file, OutputStream os) {
InputStream is = null;
StringBuilder requestParams = new StringBuilder();
try {
requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
// requestParams.append("Content-Disposition: form-data; name=\"")
// .append(file).append("\"; filename=\"")
// .append(file.getName()).append("\"")
// .append(LINE_END);
requestParams.append("Content-Disposition: form-data; name=\"file\"")
.append("; filename=\"")
.append(file.getName()).append("\"")
.append(LINE_END);
requestParams.append("Content-Type: ")
.append("image/png")
.append(LINE_END);
requestParams.append("Content-Transfer-Encoding: 8bit").append(
LINE_END);
requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容
System.out.println(requestParams.toString());
os.write(requestParams.toString().getBytes());
is = new FileInputStream(file);
byte[] buffer = new byte[1024 * 1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.write(LINE_END.getBytes());
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static Bitmap getNetBitmap(String url) {
URL imgUrl = null;
Bitmap bitmap = null;
try {
imgUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imgUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
}