Hybrid form upload using the socket to simulate HTTP (submit a form in one request and upload multiple files)

Source: Internet
Author: User
Tags add time

?????? In very many enterprise applications, we are not able to simulate HTTP composite forms (Multipart/form-data) directly through the development of language SDK package-encapsulated HTTP tools, especially during cross-language cross-platform programming. In fact, the implementation is not complicated, just to understand the HTTP protocol in the composite form of the message structure is very easy:

? ?????? Httpheader

??????? ------Time Stamp------

??????? Form Parameters 1

?????? ------Time Stamp------

?????? Form Parameters 2

????? ------Time Stamp------

????? Descriptive narrative of document 1 + binary information

???? ------Time Stamp------

???? Descriptive narrative of document 2 + binary information

?

??? Below we further illustrate this structure with a C # generation code:

???????

??????? /// <summary>

??????? /// send mixed request to server, 1: Send successfully, 0: Send failed

??????? /// </summary>

??????? /// <param name= "paranames" > Form array of the names of the parameters </param>

??????? /// <param name= "Paravalues" > array of participating values </param>

??????? /// <param name= "Files" > array of file names </param>

???????///<param name= "errmsg" > Error message </param>

??????? /// <returns></returns>

??????? Public int SendRequest (string[] paranames, string[] paravalues, string[] files, ref String errmsg)

??????? {

??????????? StringBuilder http, text;

??????????? byte [] httpbyte;

??????????? byte [] Textbyte = null;

??????????? long length = 0;

??????????? datetime now = datetime. Now;

??????????? list<byte[]> data =newList<byte[]> ();

??????????? //Construction time Stamp

??????????? string strboundary = "------------" + DateTime. Now.Ticks.ToString ("x");

??????????? byte [] boundary = Encoding. Ascii. GetBytes ("\ r \ n" + strboundary +"\ r \ n");

??????????? Length + = boundary. Length;

??????????? //Construction time Stamp

?

??????????? // Load form parameter information

??????????? if (paranames! = null)

??????????? {

??????????????? Text = new StringBuilder();

??????????????? for (int i = 0; i < Paranames. Length; i++)

??????????????? {

??????????????????? Text. Append ("--");

??????????????????? Text. Append (strboundary);// Add time stamp

??????????????????? Text. Append ("\ r \ n");

??????????????????? Text. Append ("content-disposition:form-data; Name=\ "" + paranames[i] +"\" \r\n\r\n ");

??????????????????? Text. Append (Paravalues[i]);

??????????????????? Text. Append ("\ r \ n");

??????????????? }

??????????????? string para = text. ToString ();

??????????????? Textbyte = Encoding. Ascii. GetBytes (para);

??????????????? Length + = Textbyte. Length;

??????????? }

?

??????????? // Loading File Information

??????????? if (Files = null)

??????????? {

??????????????? for (int i = 0; i < files.) Length; i++)

??????????????? {

??????????????????? FileStream FS;

??????????????????? StringBuilder sbfile =newStringBuilder();

??????????????????? Try

??????????????????? {

??????????????????????? FS = File. Open (Files[i],FileMode. Open,fileaccess. Read,fileshare. Read);

??????????????????????? if (i = = 0) sbfile. Append ("--"); // Add to File

??????????????????????? Else Sbfile. Append ("\r\n--");

??????????????????????? Sbfile. Append (strboundary);// add timestamp???????????????????????

??????????????????????? Sbfile. Append ("\ r \ n");

??????????????????????? Sbfile. Append ("content-disposition:form-data; Name=\ "");

??????????????????????? Sbfile. Append ("file");

??????????????????????? Sbfile. Append ("\"; filename=\ "");

??????????????????????? Sbfile. Append (Path. GetFileName (Files[i]));

??????????????????????? Sbfile. Append ("\" ");

?????????????????????? ? sbfile. Append ("\ r \ n");

??????????????????????? Sbfile. Append ("Content-type:");

??????????????????????? Sbfile. Append ("Application/octet-stream");

??????????????????????? Sbfile. Append ("\r\ncontent-length:");

??????????????????????? Sbfile. Append (fs. Length.tostring ());

??????????????????????? Sbfile. Append ("\ r \ n");

??????????????????????? Sbfile. Append ("\ r \ n");

??????????????????????? string temp = sbfile. ToString ();

??????????????????????? byte [] bin =Encoding. UTF8. GetBytes (temp);

??????????????????????? Data. Add (BIN);

??????????????????????? Length + = bin. Length;

??????????????????????? Length + = fs. Length;

??????????????????????? Fs. Close ();

??????????????????? }

??????????????????? Catch (Exception exc)

??????????????????? {

??? ???????????????????? ErrMsg = exc. Message.tostring ();

??????????????????????? return 0;

??????????????????? }

?

??????????????? }

??????????? }

?

??????????? //Construct HTTP Head

??????????? HTTP = new StringBuilder();

??????????? http. Append ("POST" + Ur. ToString () +"http/1.1\r\n");

??????????? http. Append ("content-type:multipart/form-data;boundary=");

??????????? http. Append (strboundary);

??????????? http. Append ("\ r \ n");

??????????? http. Append ("Host:" + ipaddress +":" + TCPPort. ToString () +"\ r \ n");

??????????? http. Append ("content-length:");

??????????? http. Append (length. ToString ());

??????????? http. Append ("\ r \ n");

??????????? http. Append ("expect:100-continue\r\n"); //Note to continue uploading the HTTP message body after receiving the continue message from the server

??????????? http. Append ("connection:keep-alive\r\n\r\n");

??????????? string strtemp = http. ToString ();

??????????? Httpbyte = Encoding. Ascii. GetBytes (strtemp);

?

??????????? Try

??????????? {

??????????????? Soc. Send (Httpbyte); " //Send HTTP headers first ????????????

????????????? ? Thread. Sleep (100);

??????????????? string check = GetResponse ();

??????????????? if (check = = Null | |!check. Contains ("Continue"))//Receive server confirmation before continuing uploading

??????????????? {

??????????????????? ErrMsg = "Theclient has successfully sent the request, but the server is not responding." ";

??????????????????? return 0;

??????????????? }

??????????????? if (paranames! = null)

??????????????? {

??????????????????? Soc. Send (Textbyte, Textbyte. Length, SocketFlags. None); //Send form Parameters

??????????????? }

??????????????? if (Files = null)

??????????????? {//send file in sequence

??????????????????? for (int i = 0; i < data.) Count; i++)

??????????????????? {

??????????????????????? int size = 0;

??????????????????????? FileStream fs =File. Open (Files[i],FileMode. Open,fileaccess. Read,fileshare. Read);

??????????????????????? Soc. Send (Data[i], data[i]. Length, SocketFlags. None);

??????????????????????? byte [] buff =newbyte[1024];

??????????????????????? Size = fs. Read (buff, 0, 1024);

??????????????????????? while (Size > 0)

??????????????????????? {

??????????????????????????? Soc. Send (buff, size, SocketFlags. None);

??????????????????????????? Size = fs. Read (buff, 0, 1024);

??????????????????????? }

??????????????????????? Fs. Close ();

??????????????????? }

??????????????? }

??????????????? Soc. Send (boundary, boundary. Length, SocketFlags. None);

??????????????? return 1;

??????????? }

??????????? Catch (Exception exc)

??????????? {

??????????????? ErrMsg = exc. Message.tostring ();

??????????????? return 0;

??????????? }

??????? }

?

Hybrid form upload using the socket to simulate HTTP (submit a form in one request and upload multiple files)

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.