Simulate post upload

Source: Internet
Author: User

Uploading and downloading files is very simple in the browser. Uploading files contains several tags in the browser. We do not know what happened in the middle, downloading files is even simpler-you only need to obtain the file address and write it in binary mode. Recently, a classmate wants to upload an app in Android, the simplest is the POST method of HTTP (fork this https://www.imququ.com/post/four-ways-to-post-data-in-http.html ).

You can first observe the HTTP header of the uploaded file:

We can see that there is an unknown request payload behind the request header. This request payload is the key to uploading files. For my understanding, refer to callback (I have already done many experiments ), the data captured in the article is similar to the data in the request payload. The knowledge payload does not contain binary streams of files.

To sum up, the main points of post object upload are as follows:

1. boundary is a random separator (contained in the request header) generated by the browser. The boundary in the request header is preceded by four "-" and the payload contains six, two more prefixes are called prefixes, and there are two prefixes at the end. (How should they be called suffixes)

2. line feed is "\ r \ n"

3. One prefix is added only at the end. If multiple files are uploaded, only the last one will have one prefix.

Add the Java implementation code (as changed on the Internet ):

  1 import java.io.ByteArrayOutputStream;  2 import java.io.File;  3 import java.io.FileInputStream;  4 import java.io.FileNotFoundException;  5 import java.io.IOException;  6 import java.io.InputStream;  7 import java.io.OutputStream;  8 import java.net.HttpURLConnection;  9 import java.net.MalformedURLException; 10 import java.net.URL; 11  12 public class Poster 13 { 14   static String boundary = "--------------7d226f700d0"; 15   static String prefix = "--"; 16   static String newLine = "\r\n"; 17   public static void main(String args[]) 18   { 19     test(); 20   } 21   private static void test() 22   { 23     try 24     { 25        26       URL url = new URL("http://1.crackme.sinaapp.com/scripts/upload.php");//post address 27       HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 28       connection.setDoInput(true); 29       connection.setDoOutput(true); 30  31       connection.setRequestProperty("Content-type","multipart/form-data;boundary="+boundary);  32       AssemblyHttp(connection.getOutputStream()); 33       InputStream ins = connection.getInputStream(); 34       byte[] b = readBuffer(ins); 35       System.out.println(new String(b)); 36     } catch (MalformedURLException e) 37     { 38       System.out.println(" URL address error "); 39     } catch (IOException e) 40     { 41       System.out.println(" URL open error "); 42     } 43   } 44   private static void AssemblyHttp(OutputStream out) 45   { 46     StringBuffer params = new StringBuffer(); 47        48     params.append(prefix+boundary + newLine); 49                                                   //name is the the key "name"‘s value in the upload form 50     params.append("Content-Disposition: form-data; name=\"myfile[]\";filename="+"\"20140821182141.jpg\""); 51     params.append(newLine);        52     params.append("Content-Type: image/jpeg"); 53     params.append(newLine+newLine); 54      55     StringBuffer params2 = new StringBuffer(); 56        57     params2.append(prefix+boundary + newLine); 58                                                                  59     params2.append("Content-Disposition: form-data; name=\"myfile[]\";filename="+"\"6b68a43308f198a375d9369a39c7ee1e.jpg\""); 60     params2.append(newLine);        61     params2.append("Content-Type: image/jpeg"); 62     params2.append(newLine+newLine); 63  64  65     File file = new File("C:\\Users\\KL\\Pictures\\20140821182141.jpg"); 66     File file2 = new File("C:\\Users\\KL\\Pictures\\6b68a43308f198a375d9369a39c7ee1e.jpg"); 67     try 68     { 69       InputStream in = new FileInputStream(file); 70       out.write(params.toString().getBytes());                    71       out.write(readBuffer(in)); 72       out.write(newLine.getBytes());            73       out.write((prefix+boundary+newLine).getBytes()); 74  75  76       InputStream in2 = new FileInputStream(file2); 77       out.write(params2.toString().getBytes());                    78       out.write(readBuffer(in2)); 79       out.write(newLine.getBytes()); 80  81       out.write((prefix+boundary + prefix).getBytes()); 82       out.flush(); 83       out.close();          84     } catch (FileNotFoundException e) 85     { 86       System.out.println(" file not found  "); 87     } catch (IOException e) 88     { 89       System.out.println(" IO Error "); 90     } 91   } 92  93  94   public static byte[] readBuffer(InputStream ins) throws IOException 95   { 96     byte b[] = new byte[1024]; 97     ByteArrayOutputStream stream = new ByteArrayOutputStream(); 98     int len = 0; 99     while((len=ins.read(b))!= -1)100     {101       stream.write(b, 0, len);102     }103     return stream.toByteArray();104   }105 }
View code

 

With Java write can see a lot of upload details, with Python third-party library is very simple, libcurl (fork this http://curl.haxx.se/libcurl/) has Python porting but a bit too large, it is not easy to configure. Poster is also a third-party library of Python, which is very convenient to use. The Code is as follows:

 1 # test_client.py 2 from poster.encode import multipart_encode 3 from poster.streaminghttp import register_openers 4 import urllib2 5  6 url = ["http://1.crackme.sinaapp.com/scripts/upload.php","http://localhost/learnPHP/scripts/upload.php"] 7  8 register_openers() 9 10 11 datagen, headers = multipart_encode({"myfile": open("C:\\Users\\KL\\Pictures\\20140821182141.jpg", "rb")})12 13 14 request = urllib2.Request(url[0], datagen, headers)15 16 print urllib2.urlopen(request).read()
View code

(Fork this http://alexliyu.blog.163.com/blog/static/162754496201252154412432)

Simulate post upload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.