最近在重构项目,去掉HttpClient,直接使用HttpURLConnection。
这里先讲一下它的POST 模拟表单上传。
1、一些常量的初始化:
public static final String BOUNDARY = "7csd4bisk2sdfk41sdfa00sskiea6d158c";
public static final String MP_BOUNDARY = "--" + BOUNDARY;
public static final String END_MP_BOUNDARY = "--" + BOUNDARY + "--";
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
2、HttpURLConnection 的初始化:
protected HttpURLConnection initConnection(URL url, String method) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
int timeoutMs =3*1000;
connection.setConnectTimeout(timeoutMs);
connection.setReadTimeout(timeoutMs);
connection.setUseCaches(false);
connection.setRequestMethod(method);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
String userAgent = "xxxxxxx";//定义自己的UserAgent,当然你也可以使用默认的。
connection.setRequestProperty("User-Agent", userAgent);
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
3、请求参数:
String url = "http://www.baidu.com/";
HashMap<String,String> param = new HashMap<String,String>();
param.put("token", "123456");//要上传的键值对
param.put("pic", "/storage/new.png");//要上传的图片
4、发送请求:
/**
* 向服务器发送数据
*
* @param requestPath
* 请求的服务器接口
* @param imgPath
* 如果有图片,就设置为图片的路径。如果没有,就设置为null
* @param bundle
* 请求参数
* @param method
* POST 或者 GET
* @return
*/
protected String sendMessage2Server(String requestPath, String imageKey, HashMap<String, Object> param, String method) {
String result = "";
try {
URL mUrl = new URL(url);
HttpURLConnection connection = initConnection(mUrl, method);
connection.connect();
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
String imgPath = param.get(imageKey) + "";
param.remove(imageKey);
paramToUpload(dos, param, requestPath);
if (!TextUtils.isEmpty(imgPath)) {
Bitmap bf = BitmapFactory.decodeFile(imgPath);
imageContentToUpload(dos, bf, "pic", "new.png");
} else {
try {
dos.write(("\r\n" + END_MP_BOUNDARY + "\r\n").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
// 根据ResponseCode判断连接是否成功
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
result = null;
} else {
// 定义BufferedReader输入流来读取URL的ResponseData
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuffer responseResult = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
responseResult.append(line);
}
result = responseResult.toString();
LogUtils.e("upload", result);
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
5、上传文本:
/**
* 上传文本
* @param baos
* @param param
* @param requestPath
*/
private void paramToUpload(OutputStream baos, HashMap<String, Object> param,) {
Set<String> set = param.keySet();
Iterator<String> keys = set.iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = param.get(key) + "";
StringBuilder temp = new StringBuilder(10);
temp.setLength(0);
temp.append(MP_BOUNDARY).append("\r\n");
temp.append("content-disposition: form-data; name=\"").append(key).append("\"\r\n\r\n");
temp.append(value).append("\r\n");
byte[] res = temp.toString().getBytes();
try {
baos.write(res);
} catch (IOException e) {
e.printStackTrace();
}
}
}
6、上传图片
/**
* 上传图片
* @param out
* @param imgpath 图片路径
* @param name
* @param fileName
*/
protected void imageContentToUpload(OutputStream out, Bitmap imgpath, String name, String fileName) {
StringBuilder temp = new StringBuilder();
temp.append(MP_BOUNDARY).append("\r\n");
temp.append("Content-Disposition: form-data; name=\"");
temp.append(name);
temp.append("\"; filename=\"").append(fileName).append("\"\r\n");
String filetype = "image/jpeg";
temp.append("Content-Type: ").append(filetype).append("\r\n\r\n");
byte[] res = temp.toString().getBytes();
try {
out.write(res);
imgpath.compress(CompressFormat.JPEG, 75, out);
out.write("\r\n".getBytes());
out.write(("\r\n" + END_MP_BOUNDARY + "\r\n").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}