您的位置:首页 > 移动开发 > Android开发

Android 模拟表单请求及servlet服务器对接示例

2016-07-20 23:15 399 查看
Android :
/**
* Created by donghe on 2016/7/19.
*/
public class NetworkFormUtil {

private static String multipart_form_data = "multipart/form-data";
private static String lineStart = "--";
private static String boundary = "****************ef5fH38L0hL9DIO";    // 数据分隔符
private static String lineEnd ="\r\n";

/**
* 直接通过 HTTP 协议提交数据到服务器,实现表单提交功能。
* @param list 上传参数
* @param actionName 上传方法名
* @param files 上传文件信息
* @return 返回请求结果
*/
public static String post(List<Map<String,Object>> list,String actionName,List<File> files) {
String actionUrl = InternetConfig.IP+actionName;
System.out.println(actionUrl);
HttpURLConnection conn = null;
DataOutputStream output = null;
BufferedReader input = null;
try {
URL url = new URL(actionUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(120000);
conn.setDoInput(true);         // 允许输入
conn.setDoOutput(true);        // 允许输出
conn.setUseCaches(false);      // 不使用Cache
conn.setRequestMethod("POST");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Content-Type", multipart_form_data + "; boundary=" + boundary);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
conn.connect();

output = new DataOutputStream(conn.getOutputStream());

addText(list, output);      // 添加文本
addImage(files, output);    // 添加图片

output.writeBytes(lineStart + boundary + lineStart + lineEnd);// 数据结束标志
output.flush();

int code = conn.getResponseCode();
System.out.println("**************result"+code);
if(code == 200) {
System.out.println("**************result");
input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String oneLine;
while((oneLine = input.readLine()) != null) {
response.append(oneLine + lineEnd);
}
return response.toString();
}else{
return null;
}

} catch (IOException e) {
throw new RuntimeException(e);
} finally {
// 统一释放资源
try {
if(output != null) {
output.close();
}
if(input != null) {
input.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}

if(conn != null) {
conn.disconnect();
}
}
}

private static void addText(List<Map<String,Object>> list, DataOutputStream output) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Map<String,Object> map:list){
for (String key:map.keySet()) {
sb.append(lineStart + boundary + lineEnd);
sb.append("Content-Disposition: form-data; name=\""+key+"\"" + lineEnd);
sb.append(lineEnd);
sb.append(map.get(key) + lineEnd);
}
}
try {
output.writeUTF(sb.toString());
//output.writeBytes(sb.toString());// 发送表单字段数据  此方法发送的中文到服务器为乱码
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("**************result" + sb);
}

private static void addImage(List<File> files, DataOutputStream output) {
for(File file : files) {
StringBuilder split = new StringBuilder();
split.append(lineStart + boundary + lineEnd);
split.append("Content-Disposition: form-data; name=\"" + "files" + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
split.append("Content-Type: " + "image/jpeg" + lineEnd);
split.append(lineEnd);
System.out.println("**************result" + split);
try {
// 发送图片数据
output.writeBytes(split.toString());
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1)
{
output.write(b, 0, n);
}
fis.close();
output.writeBytes(lineEnd);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
Servlet:public class UploadUitl {private HttpServletRequest request;private List<FileItem> list;private String upload;public UploadUitl(HttpServletRequest request){this.request=request;//创建文件项目工厂对象DiskFileItemFactory factory = new DiskFileItemFactory();//设置文件上传路径upload = "D://";//获取系统默认的临时文件保存路径,该路径为Tomcat根目录下的temp文件夹String temp = System.getProperty("java.io.tmpdir");//设置缓冲区大小为 1Mfactory.setSizeThreshold(1024*1024);//设置临时文件夹为tempfactory.setRepository(new File(temp));// 用工厂实例化上传组件,ServletFileUpload 用来解析文件上传请求ServletFileUpload servletFileUpload = new ServletFileUpload(factory);servletFileUpload.setHeaderEncoding("utf-8");//解析结果放在List中try {list = servletFileUpload.parseRequest(request);} catch (FileUploadException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** 文本域*/public JSONObject  getParameter(){JSONObject jsonObject=new JSONObject();//解析requesttry {for(FileItem item : list){//遍历所有FileItem//获取表单属性名称String name = item.getFieldName();//如果为文本域if(item.isFormField()){String value = item.getString("utf-8");//获取用户输入字符串//value=new String(item.getString().getBytes("iso-8859-1"),"utf-8");jsonObject.put(item.getFieldName(), value);System.out.println(item.getFieldName()+":"+value);}}} catch (Exception e) {e.printStackTrace();}return jsonObject;}/*** 文件域* 支持单个文件上传,能扩展*/public String getfile() {// 解析requesttry {for (FileItem item : list) {// 遍历所有FileItem// 获取表单属性名称String name = item.getFieldName();System.out.println("filename:"+name);// 如果为文件域if (!item.isFormField()) {// 获取上传文件名String filename = item.getName();// 以流的形式返回上传文件的数据内容InputStream in = item.getInputStream();//生成唯一的文件名String filename_final=makeFileName(filename);//随机生成一个路径String path_final=makePath(filename_final, upload);System.out.println("finalpath:"+new File(path_final, filename_final).toString());// 创建一个向指定 File 对象表示的文件中写入数据的文件输出流FileOutputStream outs = new FileOutputStream(new File(path_final, filename_final));int len = 0;// 定义字节数组buffer, 大小为1024byte[] buffer = new byte[1024];System.out.println("上传文件大小:" + item.getSize() + " KB");while ((len = in.read(buffer)) != -1) {// 将指定 buffer 数组中从偏移量 0 开始的 len 个字节写入此文件输出流outs.write(buffer, 0, len);}in.close(); // 关闭输入流outs.close(); // 关闭输出流return new File(path_final, filename_final).toString();}}} catch (Exception e) {e.printStackTrace();}return "";}/*** @Method: makeFileName* @Description: 生成上传文件的文件名,文件名以:uuid+"_"+文件的原始名称* @param filename*            文件的原始名称* @return uuid+"_"+文件的原始名称*/private String makeFileName(String filename) { // 2.jpg// 为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名return UUID.randomUUID().toString() + "_" + filename;}/*** 为防止一个目录下面出现太多文件,要使用hash算法打散存储** @param filename*            文件名,要根据文件名生成存储目录* @param savePath*            文件存储路径* @return 新的存储目录*/private String makePath(String filename, String savePath) {// 得到文件名的hashCode的值,得到的就是filename这个字符串对象在内存中的地址int hashcode = filename.hashCode();int dir1 = hashcode & 0xf; // 0--15int dir2 = (hashcode & 0xf0) >> 4; // 0-15// 构造新的保存目录String dir = savePath + "\\" + dir1 + "\\" + dir2; // upload\2\3 upload\3\5// File既可以代表文件也可以代表目录File file = new File(dir);// 如果目录不存在if (!file.exists()) {// 创建目录file.mkdirs();}System.out.println("dir:"+dir);return dir;}}
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android 表单 servlet