【问题标题】:cURL to C# HttpWebRequest with ParameterscURL 到带有参数的 C# HttpWebRequest
【发布时间】:2019-01-17 09:41:51
【问题描述】:

我正在尝试使用 HttpWebRequest 将以下 cURL 语句转换为 pot 请求。

curl -F datafile=@C:\Path\Students.csv -F account=accountName -F username=un -F key=acctkey -F type=1 -F format=CSV -F date=8 -F header=No -F email=email@school.org -F description=student_data_update https://webaddress.com/district_import.php

我已经尝试了许多不同的建议,以及其他网站。这个似乎最接近正确,但是我没有到达那里。我正在为 cURL 参数创建一个 postString。 postString 是根据发送给函数的参数构建的,但这就是它的样子。

    string postString = "account=accountName&type=1&format=CSV&date=8&header=No&description=student_data_update&username=un&key=acctkey&email=email@school.org";

我的代码如下所示:

            HttpWebRequest requestToServerEndpoint =
            (HttpWebRequest)WebRequest.Create(new Uri(url + @"/"));


            string boundaryString = "----SomeRandomText";

            // Set the http request header \\
            requestToServerEndpoint.Method = WebRequestMethods.Http.Post;
            requestToServerEndpoint.ContentType = "multipart/form-data; boundary=" + boundaryString;
            requestToServerEndpoint.KeepAlive = true;
            requestToServerEndpoint.Credentials = new System.Net.NetworkCredential(un, p);
            requestToServerEndpoint.Headers.Add("account", "acctName");

            // Use a MemoryStream to form the post data request,
            // so that we can get the content-length attribute.
            MemoryStream postDataStream = new MemoryStream();
            StreamWriter postDataWriter = new StreamWriter(postDataStream);

            // Include value from the myFileDescription text area in the post data
            postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
            postDataWriter.Write("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
            "myFileDescription",
            "A sample file description");

            // Include the file in the post data
            postDataWriter.Write("\r\n--" + boundaryString + "\r\n");
            postDataWriter.Write("Content-Disposition: form-data;"
            + "name=\"{0}\";"
            + "filename=\"{1}\""
            + "\r\nContent-Type: {2}\r\n\r\n",
            "myFile",
            Path.GetFileName(file),
            Path.GetExtension(file));
            postDataWriter.Flush();
            // Read the file
            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            byte[] bytes = Encoding.ASCII.GetBytes(postString);
            postDataStream.Write(bytes, 0, bytes.Length);
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                postDataStream.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            postDataWriter.Write("\r\n--" + boundaryString + "--\r\n");
            postDataWriter.Flush();

            // Set the http request body content length
            requestToServerEndpoint.ContentLength = postDataStream.Length;

            // Dump the post data from the memory stream to the request stream
            using (Stream s = requestToServerEndpoint.GetRequestStream())
            {
                postDataStream.WriteTo(s);
            }
            StreamReader responseReader = new StreamReader(requestToServerEndpoint.GetResponse().GetResponseStream());
            string responseData = responseReader.ReadToEnd();
            postDataStream.Close();
            responseReader.Close();
            requestToServerEndpoint.GetResponse().Close();

查看响应中的错误时。我的错误是:缺少帐户。 我已添加到标题中,并在我的 postString 中添加了第一个参数。我错过了什么?

【问题讨论】:

    标签: c# curl post httpwebrequest


    【解决方案1】:

    如果网络服务器设置为匿名获取文件,这样的事情应该可以解决问题。大多数服务器不会。因此,当您迁移到生产环境时,请准备好添加凭据以向服务器验证 WebClient 的身份。

    private void PostFile(string URL, string myFilePath)
    {
         // test for the file
         if (System.IO.File.Exists(myFilePath) == false)
             throw new System.IO.FileNotFoundException("Can't find " + myFilePath);
    
         // get the file
         var csvFile = System.IO.File.ReadAllBytes(myFilePath);
    
        // post the file to the server using the webclient
         using (System.Net.WebClient client = new System.Net.WebClient())
         {
            client.UploadData(URL, csvFile);
         }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多