Example code of c# calling HTTP post request to upload pictures

Time:2022-1-4

Now many B / s systems are developed through API. Generally, the server will open an API interface, and the client will call the API interface to upload pictures or files.

What are get and post? Two methods of sending requests in HTTP protocol.

What is HTTP? HTTP is a protocol based on TCP / IP about how data communicates in the world wide web.

The bottom layer of HTTP is TCP / IP. Therefore, the bottom layer of get and post is also TCP / IP, that is, both get and post are TCP links. Get and post can do the same thing. You need to add request body to get and URL parameter to post, which is technically feasible.
 
So what are the differences in the “standard answer”?

In our world wide web world, TCP is like a car. We use TCP to transport data. It is very reliable and there will never be a few pieces lost. But if the road as like as two peas looks like the same car, the world looks chaotic. The rush truck may be blocked by the truck laden with goods ahead, and the whole traffic system will be paralyzed. In order to avoid this, traffic rules were born. HTTP sets several service categories for automobile transportation, including get, post, put, delete, etc. HTTP stipulates that when executing a get request, the automobile should be labeled with get (set the method to get), and the transmitted data should be placed on the roof (URL) for recording. If it is a post request, you should affix a post label on the car and put the goods in the carriage. Of course, you can also hide some goods in the carriage during get, but it’s very disgraceful; You can also put some data on the roof during post, which makes people feel silly. HTTP is just a code of conduct, and TCP is the basic implementation of get and post.

However, we only see that HTTP requires the transmission channel (URL or requrest body) of get and post parameters. Where does the parameter size limit in the “standard answer” come from?

In my world wide web, there is another important role: transportation company. Different browsers (initiating HTTP requests) and servers (accepting HTTP requests) are different transportation companies. Although in theory, you can pile unlimited loads on the roof (add unlimited parameters to the URL). However, transportation companies are not stupid. Loading and unloading also have great costs. They will limit the single transportation volume to control risks. Too much data is a great burden on browsers and servers. The unwritten rule in the industry is that (most) browsers usually limit the URL length to 2K bytes, while (most) servers can handle URLs of up to 64K size. The excess part will not be handled. If you use the get service and hide data in the request body, the processing methods of different servers are also different. Some servers will unload and read the data for you, and some servers will ignore it directly. Therefore, although get can bring the request body, it can not be guaranteed to be received.

Well, now you know, get and post are essentially TCP links. There is no difference. However, due to the provisions of HTTP and the limitations of browser / server, they reflect some differences in the application process.

There is another major difference between get and post. To put it simply:

Get generates a TCP packet; Post generates two TCP packets.

The chief said:

For the get request, the browser will send the HTTP header and data together, and the server will respond 200 (return data);

For post, the browser sends the header first, the server responds to 100 continue, the browser sends data, and the server responds to 200 OK (return data).

In other words, get only needs a car to deliver the goods, while post has to run twice. The first time, go and say hello to the server, “Hey, I’ll deliver a batch of goods later. Open the door to meet me”, and then go back and deliver the goods.

Because post takes two steps and consumes a little more time, it seems that get is more effective than post. Therefore, the Yahoo team recommends replacing post with get to optimize website performance. But this is a pit! Be careful when jumping in. Why?

1. Both get and post have their own semantics and cannot be mixed casually.

2. According to research, under the condition of good network environment, the difference between the time of sending one packet and the time of sending two packets can be basically ignored. In the case of poor network environment, twice packet TCP has great advantages in verifying packet integrity.

3. Not all browsers send packages twice in post, and Firefox only sends them once.

Some time ago, I encountered the need to use the post request to upload pictures. I haven’t written it for a long time. Rearrange the functions to facilitate subsequent use.

In order to make the function universal, the function is encapsulated. The specific code is as follows:

public static void UploadImage(string uploadUrl,string imgPath,string fileparameter="file")
        {
            HttpWebRequest request = WebRequest.Create(uploadUrl) as HttpWebRequest;
            request.AllowAutoRedirect = true;
            request.Method = "POST";

            string boundary = DateTime. Now. Ticks. ToString("X"); //  Random separator
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            int pos = imgPath.LastIndexOf("/");
            string fileName = imgPath.Substring(pos + 1);

            //Request header information
            StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\""+fileparameter+"\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

            FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
            byte[] bArr = new byte[fs.Length];
            fs.Read(bArr, 0, bArr.Length);
            fs.Close();

            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            postStream.Write(bArr, 0, bArr.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            string content = sr.ReadToEnd();
        }

It is also convenient to use. The calling method is as follows:

Uploadimage (“upload interface address on the figure”, “local image file path”, “upload parameter name provided by the interface, no default is file”);

For example:UploadImage("http://xxx.com/upload","C:/test.jpg","upload");

This is the end of this article about the sample code of c# calling HTTP post request to upload pictures. For more information about c# HTTP post request to upload pictures, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

(excerpt) laravel layering

(excerpt) laravel layering https://laravelacademy.org/po… The core idea is layeringYou may have noticed that the key to optimizing the application directory structure is to divide the responsibilities of different components, or create different layers for different responsibilities. The controller is only responsible for receiving and responding to HTTP requests, and then calling the appropriate business logic […]