HTTP POST 経由でテキストと画像を送信しようとしていますが、常に 400 エラーが発生します。これを使用して、Telegram ボット経由で画像を送信したいと思います。この回答で提供されているコードを、テキストとバイト パラメータhttps://stackoverflow.com/a/2793153/1970613に少し変更を加えて使用しています。
エラーは何ですか?よろしくお願いします!
String param = "chat_id=mi_id&photo=";
String charset = "UTF-8";
String request = "https://api.telegram.org/bot-botCOde/sendPhoto";
URL url = new URL( request );
File binaryFile = new File("/home/joseantonio/imagen.jpg");
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
String boundary = Long.toHexString(System.currentTimeMillis());
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.setUseCaches( false );
try{
OutputStream output = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: image/jpg").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();
int responseCode2 = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + request);
System.out.println("Response Code : " + responseCode2);