JAVA HttpsConnection POST 发送图片和文字

问题描述 投票:0回答:2

我尝试通过 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);```
java image post http-status-code-400 telegram-bot
2个回答
0
投票

我相信您使用 https url 的事实是您收到错误的原因。当您提交到 https url 时,您需要处理一些不同的事情。请参阅示例此处


0
投票

我尝试修改你的代码并且它起作用了,这里是简单的SendTelegram.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.goblooge.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Files;

/**
 *
 * @author goblooge
 */
public class SendTelegram {
    public static void main(String args[]) throws Exception{
    
        String param  = "chat_id=@yourchannel&photo=";
String charset = "UTF-8"; 
String request = "https://api.telegram.org/CHNAGE_WITH_YOUR_BOT_ID/sendPhoto?chat_id=@yourchannel";
URL url = new URL( request );
File binaryFile = new File("huda.jpg");
File ff = binaryFile;
 String content_type = Files.probeContentType(binaryFile.toPath());

System.out.println(binaryFile.getAbsolutePath());
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
String boundary = Long.toHexString(System.currentTimeMillis());
String CrLf = "\r\n";
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 );


String postData = "";

            InputStream imgIs = new FileInputStream(ff);
            byte[] imgData = new byte[imgIs.available()];
            imgIs.read(imgData);

            String message1 = "";
            message1 += "-----------------------------"+boundary + CrLf;
            message1 += "Content-Disposition: form-data; name=\"photo\"; filename=\""+ff.getName()+"\""
                    + CrLf;
            
            
            message1 += "Content-Type: "+content_type+ CrLf;
            message1 += CrLf;

            // the image is sent between the messages in the multipart message.

            String message2 = "";
            message2 += CrLf + "-----------------------------"+boundary+"--"
                    + CrLf;

            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=---------------------------"+boundary);
            // might not need to specify the content-length when sending chunked
            // data.
            conn.setRequestProperty("Content-Length", String.valueOf((message1
                    .length() + message2.length() + imgData.length)));


    OutputStream os = conn.getOutputStream();
    System.out.println(message1);
            os.write(message1.getBytes());
            
    // SEND THE IMAGE
            int index = 0;
            int size = 1024;
            do {
                System.out.println("write:" + index);
                if ((index + size) > imgData.length) {
                    size = imgData.length - index;
                }
                os.write(imgData, index, size);
                index += size;
            } while (index < imgData.length);
            System.out.println("written:" + index);

            System.out.println(message2);
            os.write(message2.getBytes());
            os.flush();

            System.out.println("open is");
                    InputStream is = conn.getInputStream();

            
            
            char buff = 512;
            int len;
            byte[] data = new byte[buff];
            do {
                System.out.println("READ");
                len = is.read(data);

                if (len > 0) {
                    System.out.println(new String(data, 0, len));
                }
            } while (len > 0);

            System.out.println("DONE");
    
    /*
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);

    
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"photo\" filename=\""+binaryFile.getName()+"\"").append(CRLF);
    writer.append("Content-Type: "+content_type+"; 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);
    
    

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.