Unity C# 网络学习(七)——HTTP(二)

Unity C# 网络学习(七)——HTTP(二)

一.Post请求

        HttpWebRequest httpWebRequest = WebRequest.CreateHttp("http://192.168.1.103:8080/Http_Server/");
        httpWebRequest.Method = WebRequestMethods.Http.Post;
        httpWebRequest.Timeout = 2000;
        httpWebRequest.ContentType = "application/x-www-form-urlencoded";
        string str = "Name=zzs&ID=2";
        byte[] buffer = Encoding.UTF8.GetBytes(str);
        httpWebRequest.ContentLength = buffer.Length;
        Stream s = httpWebRequest.GetRequestStream();
        s.Write(buffer,0,buffer.Length);
        s.Close();
        HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
        if (httpWebResponse == null)
            return;
        Debug.Log(httpWebResponse.StatusCode);
        httpWebResponse.Close();

二.HTTP上传数据

    private void Start()
    {
    
    
        //上传数据不需要加上上传数据的名称
        HttpWebRequest httpWebRequest = WebRequest.CreateHttp(
            new Uri("http://192.168.1.103:8080/Http_Server/"));
        httpWebRequest.Method = WebRequestMethods.Http.Post;
        httpWebRequest.Timeout = 5000 * 100;
        //如果上传需要身份验证,需要同时设置httpWebRequest.PreAuthenticate = true;
        httpWebRequest.Credentials = new NetworkCredential("zzs", "123");
        httpWebRequest.PreAuthenticate = true;
        //设置内容的类型(复合类型,设置边界条件)
        httpWebRequest.ContentType = "multipart/form-data;boundary=zzs";

        //文件数据前的头部信息
        //--边界字符串
        //Content-Disposition:form-data;name="字段名字,之后写入文件的二进制数据和该字段名相对应";filename="传到服务器上使用的文件名"
        //Content-Type:application/octet-stream由于我们传二进制文件,所以这里使用二进制
        string head = "--zzs\r\n" +
                      "Content-Disposition:form-data;name=\"file\";filename=\"http上传的文件.jpg\"\r\n" +
                      "Content-Type:application/octet-stream\r\n\r\n";
        byte[] headBytes = Encoding.UTF8.GetBytes(head);
        //结束的边界信息
        //--边界字符串--
        byte[] endBytes = Encoding.UTF8.GetBytes("\r\n--zzs--\r\n");

        using (FileStream fs = new FileStream(Application.streamingAssetsPath + "/test.jpg", FileMode.Open))
        {
    
    
            byte[] buffer = new byte[10240];
            int len = fs.Read(buffer, 0, buffer.Length);
            Stream s = httpWebRequest.GetRequestStream();
            s.Write(headBytes, 0, headBytes.Length);
            while (len > 0)
            {
    
    
                s.Write(buffer, 0, len);
                len = fs.Read(buffer, 0, buffer.Length);
            }

            s.Write(endBytes, 0, endBytes.Length);
            s.Close();
        }

        HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
        if (httpWebResponse == null)
            return;
        Debug.Log(httpWebResponse.StatusCode == HttpStatusCode.OK ? "上传成功!" : "上传失败!");
    }

三.HTTP上传数据封装

    public async void UpLoadFile(string fileName, string path, Action<HttpStatusCode> action)
    {
    
    
        HttpStatusCode code = HttpStatusCode.OK;
        await Task.Run(() =>
        {
    
    
            try
            {
    
    
                HttpWebRequest httpWebRequest = WebRequest.CreateHttp(new Uri(RootPath));
                httpWebRequest.Method = WebRequestMethods.Http.Post;
                httpWebRequest.Timeout = 5000 * 100;
                httpWebRequest.Credentials = new NetworkCredential(UserName, Password);
                httpWebRequest.PreAuthenticate = true;
                httpWebRequest.ContentType = "multipart/form-data;boundary=zzs";

                string head = "--zzs\r\n" +
                              "Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\n" +
                              "Content-Type:application/octet-stream\r\n\r\n";
                head = string.Format(head, fileName);
                byte[] headBytes = Encoding.UTF8.GetBytes(head);
                //结束的边界信息
                //--边界字符串--
                byte[] endBytes = Encoding.UTF8.GetBytes("\r\n--zzs--\r\n");

                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
    
    
                    Stream s = httpWebRequest.GetRequestStream();
                    byte[] buffer = new byte[10240];
                    int len = fs.Read(buffer, 0, buffer.Length);
                    s.Write(headBytes,0,headBytes.Length);
                    while (len>0)
                    {
    
    
                        s.Write(buffer,0,len);
                        len = fs.Read(buffer, 0, buffer.Length);
                    }
                    s.Write(endBytes,0,endBytes.Length);
                    s.Close();
                }

                HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
                if (httpWebResponse == null)
                    return;
                code = httpWebResponse.StatusCode;
            }
            catch (WebException we)
            {
    
    
                Debug.Log(we);
                code = HttpStatusCode.InternalServerError;
            }
        });
        action?.Invoke(code);
    }

猜你喜欢

转载自blog.csdn.net/zzzsss123333/article/details/125456792