首页 > 解决方案 > Httpwebrequest C#:远程服务器返回错误:(400) Bad Request

问题描述

C# 控制台应用程序:

我将表单数据发布到服务器,该服务器从本地 PC 获取文件并将其复制到服务器上的文件夹中。当我用 curl 调用这个命令时

curl --location --request POST "http://8.8.8.8:8080/upload" --form "file=@"D:/Testfile.txt""

它工作得很好。但是,我需要将其转换为 httpwebrequest(不是 httpclient)。

这是我到目前为止所尝试的。服务器需要两个参数“文件”及其路径。这是 Python 中的服务器端实现。

@app.post("/upload")
async def create_upload_file(file: UploadFile = File(...)):
    content = file.file.read()
    try:
        with open(f"{temporary_folder}\\{file.filename}",'wb+') as f:
            f.write(content)
            f.close()
        return {"filename": file.filename}
    except Exception as e:
        logger.error("Upload didn Work"+ str(e))
        raise HTTPException(status_code=400, detail=e)

这是我在 C#.net 中尝试过的。

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{

    public class WebRequestPostExample
    {

        public static void Main()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            
            var postData = "{file: \"D:/Testfile.txt\" }";
            byte[] data = Encoding.UTF8.GetBytes(postData);
          
            var url = "http://8.8.8.8:8080/upload";

            var httpRequest = (HttpWebRequest)WebRequest.Create(url);
            httpRequest.Credentials = new NetworkCredential("Username", "password");
         
            httpRequest.Method = "POST";
            httpRequest.Headers["Authorization"] = "Basic";
            httpRequest.KeepAlive = true;
            
            httpRequest.ContentLength = data.Length;

            httpRequest.ContentType = "multipart/form-data";

            using (var streamWriter = httpRequest.GetRequestStream())
            {
                streamWriter.Write(data, 0, data.Length);
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }

            Console.WriteLine(httpResponse.StatusCode);


        }
    }
}

而且我总是收到错误“400 Bad request”。我厌倦了不同的方法并在这里查看了不同的问题,但找不到任何解决方案。任何形式的帮助将不胜感激。

非常感谢。

标签: pythonc#.netvisual-studiohttpwebrequest

解决方案


推荐阅读