Indy Post to discord webhook给出了错误的请求400

时间:2018-05-09 13:27:53

标签: delphi post webhooks indy discord

我正在尝试使用Discord webhook向Discord频道发送消息。唯一的问题是我不断收到namespace MyNamespace { class MyClass { public: enum class MyEnum_t { VALUE_0 = 0x0, VALUE_1 = 0x1, VALUE_2 = 0x2, VALUE_3 = 0x4, VALUE_4 = 0x8 }; }; inline MyClass::MyEnum_t operator|(MyClass::MyEnum_t lhs, MyClass::MyEnum_t rhs) { return static_cast<MyEnum_t>(static_cast<std::uint8_t>(lhs) | static_cast<std::uint8_t>(rhs)); } } 错误。

我有以下代码:

400 Bad Request

我不知道我做错了什么。

1 个答案:

答案 0 :(得分:2)

您没有使用正确的TIdHTTP.Post()方法发布数据。

您正在使用以Post()作为输入的重载TStrings方法。该方法用于以application/x-www-webform-urlencoded格式发送HTML网络表单。但您将Request.ContentType属性设置为'multipart/form-data',因此您发送的格式错误的请求。

要以multipart/form-data格式发送数据,您需要使用以Post()作为输入的重载TIdMultipartFormDataStream方法,例如:

procedure TForm1.btn1Click(Sender: TObject);
var
  params: TIdMultipartFormDataStream;
begin
  params := TIdMultipartFormDataStream.Create;
  try
    params.AddFormField('content', 'Test');
    params.AddFormField('username', 'testname');
    params.AddFormField('avatar_url', 'https://i.imgur.com/ivUiaOr.png');

    httpclient1.Request.UserAgent := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36';
    httpclient1.Post('https://discordapp.com/api/webhooks/443763508073594880/r8Oba0ws7WeN-n57TeF6BF6CKFFjviov6XMrMVVDUY_G18zmmY7VUwZqCiAOs9nz-CyC', params);
  finally
    params.Free;
  end;
end;

如果您没有上传实际文件(使用TIdMultipartFormDataStream.AddFile()方法执行此操作),则可以使用'application/json'TStream格式发布文本字段(不是TStringList),例如:

procedure TForm1.btn1Click(Sender: TObject);
var
  params: TStringStream;
begin
  params := TStringStream.Create('{"content": "Test", "username": "testname", "avatar_url": "https://i.imgur.com/ivUiaOr.png"}', TEncoding.UTF8);
  try
    httpclient1.Request.ContentType := 'application/json';
    httpclient1.Request.UserAgent := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36';
    httpclient1.Post('https://discordapp.com/api/webhooks/443763508073594880/r8Oba0ws7WeN-n57TeF6BF6CKFFjviov6XMrMVVDUY_G18zmmY7VUwZqCiAOs9nz-CyC', params);
  finally
    params.Free;
  end;
end;