File upload of Http communication in Android

1. Create a Dynamic Web project and specify its server. We use Tomcat7.0 here, and create a new index.jsp file with the following contents:

  

<%@ 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. Create a new Servlet corresponding to the form action.

 

 

/**
 * Servlet implementation class Upload
 */
@WebServlet("/Upload")
@MultipartConfig(location="G:\\") //The address of the specified file upload here is the G drive
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");
	}

}

   The Web has been configured here, open the browser and run it again

 



  After selecting the file and submitting it, the file is located in the local G drive. When submitting, open the Google browser developer tool to view the header, that is, the request header information, to help the development of the Android client in the future.

Parameter comparison when setting connection request

 


 
 3. The Android client creates an 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 ();
        }

    }
}

 
 

  

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326869518&siteId=291194637