Android中的Http通信之文件上传

1.创建一个Dynamic Web project工程,指定其服务器,我们这里用的是Tomcat7.0,新建index.jsp文件,其内容如下:

  

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<form action="Upload" method="post" enctype="multipart/form-data">
			<input type="file" name="file" ></br>
			<input type="submit" name="submit"></br>
	</form>
</body>
</html>

 2.新建一个form action对应的Servlet。

/**
 * Servlet implementation class Upload
 */
@WebServlet("/Upload")
@MultipartConfig(location="G:\\") //指定文件上传的地址这里是G盘
public class Upload extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Upload() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Part part = request.getPart("file");
		part.write("dsa.jpg");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.write("upload success");
	}

}

   到这里Web就已经配置完了,打开浏览器运行一遍


Android中的Http通信之文件上传
  选择完文件并提交这文件就在本地的G盘下了,提交时,打开Google浏览器开发者工具查看header,即请求头信息,以助在后面Android客户端开发

设置连接请求时的参数对照

Android中的Http通信之文件上传
 
 3.Android客户端创建一个UploadThread

package com.pt.http01;

import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by 韬 on 2016-05-14.
 */
public class UploadThread extends Thread{

    private String url;
    private String filename;
    private static final String TAG = "UploadThread";
    public UploadThread(String url,String filename){
        this.url = url;
        this.filename = filename;
    }

    @Override
    public void run() {
        String boundary = "---------------------------7e02933960556";
        String prefix = "--";
        String end = "\r\n";

        try {
            URL httpurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpurl.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + boundary);
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.writeBytes(prefix + boundary + end);
            out.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + "dsa.jpg" + "\"" + end);
            FileInputStream inputStream = new FileInputStream(new File(filename));
            byte[] data = new byte[1024*4];
            int len = 0;
            while ((len = inputStream.read(data)) != -1){
                out.write(data,0,len);
            }
            out.writeBytes(end);
            out.writeBytes(prefix + boundary + prefix + end);
            out.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String str;
            while((str = reader.readLine()) != null){
                sb.append(str);
            }
            Log.i(TAG, "run: \"reponse\"" + sb.toString());
            if (out != null){
                out.close();
            }
            if(reader != null){
                reader.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

 
 

  

相关推荐