今天在项目中发现,服务器上传数据只能通过模拟form表单的形式提交。所以比较纠结。后来摸索一段时间。最终磕磕绊绊的成功了。在这发布mark一下。
首先,假如我们有个html文件为如下所示:
New DocumentFile Upload with Jersey
Select a file :
我们现在就要通过安卓来模拟上面的html,实现与服务器的数据交互。相关代码如下:
public static String sendFileAndJson(String urlPath, String filePath,
String newName,String param) throws Exception {
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型
try {
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(TIMEOUT);// 连接主机的超时时间(单位:毫秒)
conn.setReadTimeout(TIMEOUT);// 设置从主机读取数据的超时时间
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码为UTF-8
conn.setRequestProperty("connection", "keep-alive");// 设置维持长连接
conn.setRequestProperty("Cache-Control", "no-cache"); // 禁止缓存
// 设置Content-Type=“multipart/form-data",模拟表单提交方式
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
// 封装需要上传的数据,这里重点注意: name里面的值"json"为服务器端需要key 只有这个key 才可以得到对应的参数
StringBuilder textEntity = new StringBuilder();
textEntity.append(PREFIX);
textEntity.append(BOUNDARY);
textEntity.append(LINE_END);
textEntity.append("Content-Disposition: form-data; name=\"json\"" + LINE_END);
textEntity.append(LINE_END);
textEntity.append(param);
textEntity.append(LINE_END);
dos.write(textEntity.toString().getBytes());
/**
* 把文件包装并且上传
*/
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对 应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + newName + "\""
+ LINE_END);
sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
// 读入文件流
InputStream is = new FileInputStream(filePath);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取返回结果
*/
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
System.out.print("返回结果--------->" + result);
} catch (MalformedURLException e) {
e.printStackTrace();
result = e.toString();
} catch (IOException e) {
e.printStackTrace();
result = e.toString();
}
return result;
}