python - 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”。我厌倦了不同的方法并在这里查看了不同的问题,但找不到任何解决方案。任何形式的帮助将不胜感激。
非常感谢。
解决方案
推荐阅读
- typescript - 缩小打字稿中的generec类型
- java - 带有 Bootstrap 和 Thymeleaf 页面装饰的 SpringMVC
- php - 用于博客内容的 Home.php 无法检索页面标题 - Wordpress
- java - Android Studio Fragments 和 Adapter 没有连接
- r - 绘制 R 中因子的时间序列数据列表
- javascript - 如何在 Spring Boot 中解析 html 内容
- python - Python 请求行为怪异
- kiwi-tcms - Gitlab集成正确的URL配置
- python - 如何根据条件阈值pyspark计算列的累积总和
- sas - 将 SQL 更新转换为 SAS DI