[Upload files based on HttpURLConnection to simulate Http protocol]

Permalink:  http://gaojingsong.iteye.com/blog/2414484

Preview article: [Http file upload protocol analysis]

The first is the request header:

The most important content is Content-Type, and his content is:

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary6TAB8KxvuJTZYfUn

Separate the different parameters with a semicolon: 

The first parameter multipart/form-data is required, which means that there are attachments in the submitted form 

The second parameter boundary represents the dividing line, which will be used to divide different request parameters in the request body 

As for other parameters, you can directly imitate and pass them when you write your own request.

 

core code

package com.example.fileupload.controller;

 

import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.HashMap;

import java.util.Set;

 

public class HttpUrlConnectionDemo {

 

/**

* @param args

*/

public static void main(String[] args) {

// upload file test

String actionURL ="http://localhost:9090/mgr/upload";

String uploadFile="c:/examples.cfg";

HashMap<String, String> parameters = new HashMap<String, String>();

parameters.put("email", "[email protected]");

singleFileUploadWithParameters( actionURL,  uploadFile, parameters );

 

}

 

/** 

* @author Johnson 

* @method singleFileUploadWithParameters 

* @description A method for uploading a single file and passing parameters 

* @param actionURL The URL address of the uploaded file includes the URL 

* @param fileType file type (enumeration type) 

* @param uploadFile upload file path string 

* @return String("" if no response get) 

* @attention upload file name is file (server parsing) 

* */  

public static String singleFileUploadWithParameters(String actionURL, String uploadFile, 

HashMap<String, String> parameters){  

   String end = "\r\n";  

   String twoHyphens = "--";  

   String boundary = "---------------------------7e0dd540448";  

   String response = "";  

   try{  

       URL url = new URL(actionURL);  

       HttpURLConnection connection = (HttpURLConnection)url.openConnection();  

       //Sending a post request requires the following two lines  

       connection.setDoInput(true);  

       connection.setDoOutput(true);  

       //set request parameters  

       connection.setUseCaches(false);  

       connection.setRequestMethod("POST");  

       connection.setRequestProperty("Connection", "Keep-Alive");  

       connection.setRequestProperty("Charset", "UTF-8");  

       connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);  

       //Get the request content output stream                          

       DataOutputStream ds = new DataOutputStream(connection.getOutputStream());  

       String fileName = uploadFile.substring(uploadFile.lastIndexOf("/") + 1);  

       //Start writing form format content  

       // write parameters  

       Set<String> keys = parameters.keySet();  

       for(String key : keys){  

           ds.writeBytes(twoHyphens + boundary + end);  

           ds.writeBytes("Content-Disposition: form-data; name=\"");  

           ds.write(key.getBytes());  

           ds.writeBytes("\"" + end);  

           ds.writeBytes(end);  

           ds.write(parameters.get(key).getBytes());  

           ds.writeBytes(end);  

       }  

       //write file  

       ds.writeBytes(twoHyphens + boundary + end);  

       ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\"; " + "filename=\"");  

       //Prevent Chinese garbled characters  

       ds.write(fileName.getBytes());  

       ds.writeBytes("\"" + end);  

       ds.writeBytes("Content-Type: text/plain" + end);  

       ds.writeBytes(end);  

       //Read the file according to the path  

       FileInputStream fis = new FileInputStream(uploadFile);  

       byte[] buffer = new byte[1024];  

       int length = -1;  

       while((length = fis.read(buffer)) != -1){  

           ds.write(buffer, 0, length);  

       }  

       ds.writeBytes(end);  

       fis.close();  

       ds.writeBytes(twoHyphens + boundary + twoHyphens + end);  

       ds.writeBytes(end);  

       ds.flush();  

       try{  

           // Get the response from the URL  

           BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));  

           String s = "";  

           String temp = "";  

           while((temp = reader.readLine()) != null){  

               s += temp;  

           }  

           response = s;  

           reader.close();  

       }catch(IOException e){  

           e.printStackTrace ();  

           System.out.println("No response get!!!");  

       }  

       ds.close();  

   }catch(IOException e){  

       e.printStackTrace ();  

       System.out.println("Request failed!");  

   }  

   return response;  

}  

 

}

 

 

Result verification:



 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326022865&siteId=291194637