Android通过Post上传数据和图片到Servlet

来源:互联网 发布:淘宝助理上传中断 编辑:程序博客网 时间:2024/05/29 10:34

之前在做Android服务端客户端Demo的时候,暂时使用的Servlet来从当服务端,这样的话,当我们需要从Android客户端与服务端进行数据交互的时候,需要从客户端上传数据到Servlet.下面是实例代码:

Android上传数据到Servlet代码

                        //用于提交数据的client                        HttpClient client = new DefaultHttpClient();                        //这是提交的服务端地址                        String url = "http://192.168.1.101:8080/FaceServer/JWOKServlet";                        //采用的是Post方式进行数据的提交                        HttpPost post = new HttpPost(url);                        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();                        //这里就是提交的数据,你在服务端就可以通过request.getParameter("字段名称")                        paramsList.add(new BasicNameValuePair("id",id));                        paramsList.add(new BasicNameValuePair("name", name));                         paramsList.add(new BasicNameValuePair("jingdu", jingdu));                        paramsList.add(new BasicNameValuePair("weidu", weidu));                        try {                            post.setEntity(new UrlEncodedFormEntity(paramsList,                                    HTTP.UTF_8));                            HttpResponse response = client.execute(post);                            if (response.getStatusLine().getStatusCode() == 200) {                                ByteArrayOutputStream outStream = new ByteArrayOutputStream();                                InputStream in = response.getEntity()                                        .getContent();                                byte[] data = new byte[4096];                                int count = -1;                                while ((count = in.read(data, 0, 4096)) != -1)                                    outStream.write(data, 0, count);                                data = null;                                //这是服务端返回的数据                                String content = new String(outStream                                        .toByteArray(), "utf-8");}                        catch(Exception ex){                              }

上面就是Android上传数据到Servlet的代码,其中采用的BasicNameValuePair来进行数据的包装。

Android上传图片到Servlet

public class UploadUtil {    private static final String TAG = "uploadFile";    private static final int TIME_OUT = 10 * 1000;     private static final String CHARSET = "utf-8";     public static String post(String url, Map<String, String> params, Map<String, File> files)            throws IOException {        String BOUNDARY = java.util.UUID.randomUUID().toString();        String PREFIX = "--", LINEND = "\r\n";        String MULTIPART_FROM_DATA = "multipart/form-data";        String CHARSET = "UTF-8";        URL uri = new URL(url);        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();        conn.setReadTimeout(10 * 1000);         conn.setDoInput(true);        conn.setDoOutput(true);        conn.setUseCaches(false);         conn.setRequestMethod("POST");        conn.setRequestProperty("connection", "keep-alive");        conn.setRequestProperty("Charsert", "UTF-8");        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);        StringBuilder sb = new StringBuilder();        for (Map.Entry<String, String> entry : params.entrySet()) {            sb.append(PREFIX);            sb.append(BOUNDARY);            sb.append(LINEND);            sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);            sb.append(LINEND);            sb.append(entry.getValue());            sb.append(LINEND);        }        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());        outStream.write(sb.toString().getBytes());        if (files != null)            for (Map.Entry<String, File> file : files.entrySet()) {                StringBuilder sb1 = new StringBuilder();                sb1.append(PREFIX);                sb1.append(BOUNDARY);                sb1.append(LINEND);                sb1.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""                        + file.getValue().getName() + "\"" + LINEND);                sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);                sb1.append(LINEND);                outStream.write(sb1.toString().getBytes());                InputStream is = new FileInputStream(file.getValue());                byte[] buffer = new byte[1024];                int len = 0;                while ((len = is.read(buffer)) != -1) {                    outStream.write(buffer, 0, len);                }                is.close();                outStream.write(LINEND.getBytes());            }       byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();        outStream.write(end_data);        outStream.flush();        int res = conn.getResponseCode();        InputStream in = conn.getInputStream();        StringBuilder sb2 = new StringBuilder();        if (res == 200) {            int ch;            while ((ch = in.read()) != -1) {                sb2.append((char) ch);            }        }        outStream.close();        conn.disconnect();        return sb2.toString();    }}

在上面的代码中,url就是我们服务端用以接受图片的地址,params就是提交的参数集合,files就是我们上传的图片的map,这里也可以是别的文件。

Servlet端用以接受图片的代码

    protected void doPost(HttpServletRequest request,            HttpServletResponse response) throws ServletException, IOException {        response.setCharacterEncoding("utf-8");        DiskFileItemFactory factory = new DiskFileItemFactory();        String fileName = "";        // 获取文件上传需要保存的路径,upload文件夹需存在。        //这是我本地用以存储图片的文件夹路劲        String path = "D:\\Face detection\\image";        // 设置暂时存放文件的存储室,这个存储室可以和最终存储文件的文件夹不同。因为当文件很大的话会占用过多内存所以设置存储室。        factory.setRepository(new File(path));        // 设置缓存的大小,当上传文件的容量超过缓存时,就放到暂时存储室。        factory.setSizeThreshold(1024 * 1024);        // 上传处理工具类(高水平API上传处理?)        ServletFileUpload upload = new ServletFileUpload(factory);        try {            // 调用 parseRequest(request)方法 获得上传文件 FileItem 的集合list 可实现多文件上传。            List<FileItem> list = (List<FileItem>) upload.parseRequest(request);            for (FileItem item : list) {                // 获取表单属性名字。                String name = item.getFieldName();                // 如果获取的表单信息是普通的文本信息。即通过页面表单形式传递来的字符串。                if (item.isFormField()) {                    // 获取用户具体输入的字符串,                    String value = item.getString();                    request.setAttribute(name, value);                }                // 如果传入的是非简单字符串,而是图片,音频,视频等二进制文件。                else {                    // 获取路径名                    String value = item.getName();                    // 取到最后一个反斜杠。                    int start = value.lastIndexOf("\\");                    // 截取上传文件的 字符串名字。+1是去掉反斜杠。                    String filename = value.substring(start + 1);                    request.setAttribute(name, filename);                    /*                     * 第三方提供的方法直接写到文件中。 item.write(new File(path,filename));                     */                    // 收到写到接收的文件中。                    OutputStream out = new FileOutputStream(new File(path,                            filename));                    System.out.println("..........."+filename);                    fileName = filename;                    InputStream in = item.getInputStream();                    int length = 0;                    byte[] buf = new byte[1024];                    while ((length = in.read(buf)) != -1) {                        out.write(buf, 0, length);                    }                    in.close();                    out.close();                }            }        } catch (Exception e) {            e.printStackTrace();        }    }

当然,上面代码要运行成功的话还需要下载这三个jar文件到你的服务端的WEB-INF下面的lib中。这是下载地址:jar包下载地址,密码:7xha

0 0
原创粉丝点击