电报,Java:上传文件以发送到sendAnimation

电报,Java:上传文件以发送到sendAnimation,java,httpurlconnection,telegram,telegram-bot,Java,Httpurlconnection,Telegram,Telegram Bot,在sendAnimation中有一个方法。有两个必须的参数:chat_id和animation。动画的描述如下: 类型:InputFile或String 描述:要发送的动画。将文件id作为字符串传递,以发送 存在于建议的电报服务器上,将HTTP URL作为 用于电报的字符串,用于从Internet获取动画或上载动画 使用多部分/表单数据的新动画。有关发送文件的更多信息» 我有一个本地.gif文件要发送。看起来我需要使用多部分/表单数据方法。我不明白那是什么方法。我签出了InputFile类型的描

在sendAnimation中有一个方法。有两个必须的参数:chat_id和animation。动画的描述如下:

类型:InputFile或String

描述:要发送的动画。将文件id作为字符串传递,以发送 存在于建议的电报服务器上,将HTTP URL作为 用于电报的字符串,用于从Internet获取动画或上载动画 使用多部分/表单数据的新动画。有关发送文件的更多信息»

我有一个本地.gif文件要发送。看起来我需要使用多部分/表单数据方法。我不明白那是什么方法。我签出了InputFile类型的描述:

InputFile此对象表示要创建的文件的内容 上传。必须以通常的方式使用多部分/表单数据过帐 这些文件是通过浏览器上传的

同样,他们写了关于多部分/表单数据的东西,但没有写确切的内容

我想也许我可以使用sendDocument方法上传一个文件,但是上传的文档也必须是InputFile类型


如何从本地.gif文件中生成InputFile对象?我可以将其转换为Java的InputStream,但仅此而已

简单多部分/表单数据只是发送数据的一种加密类型表单中有三种加密类型:

application/x-www-form-url编码为默认值 多部分/表单数据 文本/纯文本 有关多部分/表单数据的更多信息,请检查此

我不知道java中的GIF对象是什么类型,但是我们把它看作二进制文件,然后简单地使用POST请求:
String url = "uploading url";
String charset = "UTF-8";
String param = "value";
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.

URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

try {
    OutputStream output = connection.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
     // Send binary file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
    writer.append(CRLF).flush();
    Files.copy(binaryFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // End of multipart/form-data.
    writer.append("--" + boundary + "--").append(CRLF).flush();
}

// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200

你好谢谢你的回复。我不知道该将gif发送到哪个地址。表示url变量的值应该是多少。电报服务器?但是哪一个呢?我猜出来了。地址是…sendAnimation。但我找到了一个较短的版本:。你的版本快了吗?还是你认为可以使用另一个?