Java 中的 WebAPI POST,正文中包含文件

发布于 2025-01-09 12:52:59 字数 5969 浏览 0 评论 0原文

我在 Java 中调用 webAPI 时遇到问题。基本上,我必须上传一个文件(xml 或 pdf),但我无法让它工作。我在 Postman 中尝试过,它有效,我必须在正文中放入文件名和文件内容< img src="https://i.sstatic.net/79UpO.jpg" alt="在此处输入图像描述">

在此处输入图像说明

在此处输入图像描述

如果我声明文件数据作为文件(见图 3)它可以工作。我尝试用 Java 来做,但找不到方法。我尝试了很多来自网络的片段,但最多当我运行它们时,我收到错误 500。

到目前为止我得到的代码是

package api_post;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class API_POST {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
  String charset = "UTF-8";
    File uploadFile1 = new File("[fileWithPath]");
    String requestURL = "";
    requestURL = "[URL]";
    
    try {
        MultipartUtility multipart = new MultipartUtility(requestURL, charset);
         
         
        multipart.addFormField("username", "[user]");
        multipart.addFormField("password", "[pwd]");
        multipart.addFormField("owner", "[owner]");
        multipart.addFormField("destination", "[destination]");
         
        multipart.addFilePart("fileData", uploadFile1);

        List<String> response = multipart.finish();
         
        System.out.println("SERVER REPLIED:");
         
        for (String line : response) {
            System.out.println(line);
        }
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

public static class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;

public MultipartUtility(String requestURL, String charset) throws IOException {
    this.charset = charset;
     
    // creates a unique boundary based on time stamp
    boundary = "===" + System.currentTimeMillis() + "===";
     
    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);

    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
            true);
}

/**
 * Adds a form field to the request
 * @param name field name
 * @param value field value
 */
public void addFormField(String name, String value) {
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
            .append(LINE_FEED);
    writer.append("Content-Type: text/plain; charset=" + charset).append(
            LINE_FEED);
    writer.append(LINE_FEED);
    writer.append(value).append(LINE_FEED);
    writer.flush();
}

/**
 * Adds a upload file section to the request
 * @param fieldName name attribute in <input type="file" name="..." />
 * @param uploadFile a File to be uploaded
 * @throws IOException
 */
public void addFilePart(String fieldName, File uploadFile) throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
            "Content-Disposition: form-data; name=\"" + fieldName
                    + "\"; filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append(
            "Content-Type: "
                    + URLConnection.guessContentTypeFromName(fileName))
            .append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();
     
    writer.append(LINE_FEED);
    writer.flush();    
}

/**
 * Adds a header field to the request.
 * @param name - name of the header field
 * @param value - value of the header field
 */
public void addHeaderField(String name, String value) {
    writer.append(name + ": " + value).append(LINE_FEED);
    writer.flush();
}
 
/**
 * Completes the request and receives response from the server.
 * @return a list of Strings as response in case the server returned
 * status OK, otherwise an exception is thrown.
 * @throws IOException
 */
public List<String> finish() throws IOException {
    List<String> response = new ArrayList<String>();

    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        System.out.println("Entrato");
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }

    return response;
}}}

有人能帮助我吗?

I have a problem calling a webAPI in Java. Basically, I have to upload a file (xml or pdf) but I cannot get it work. I tried in Postman and it works, I had to put in the body the filename and the content of the fileenter image description here

enter image description here

enter image description here

If I declare the filedata as file (see pic. 3) it works. I tried to do it in Java but I cannot find a way to do it. I tried many snippets from the web buut at best when I run them I get error 500.

The code I got so far is

package api_post;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class API_POST {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
  String charset = "UTF-8";
    File uploadFile1 = new File("[fileWithPath]");
    String requestURL = "";
    requestURL = "[URL]";
    
    try {
        MultipartUtility multipart = new MultipartUtility(requestURL, charset);
         
         
        multipart.addFormField("username", "[user]");
        multipart.addFormField("password", "[pwd]");
        multipart.addFormField("owner", "[owner]");
        multipart.addFormField("destination", "[destination]");
         
        multipart.addFilePart("fileData", uploadFile1);

        List<String> response = multipart.finish();
         
        System.out.println("SERVER REPLIED:");
         
        for (String line : response) {
            System.out.println(line);
        }
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

public static class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;

public MultipartUtility(String requestURL, String charset) throws IOException {
    this.charset = charset;
     
    // creates a unique boundary based on time stamp
    boundary = "===" + System.currentTimeMillis() + "===";
     
    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);

    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
            true);
}

/**
 * Adds a form field to the request
 * @param name field name
 * @param value field value
 */
public void addFormField(String name, String value) {
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
            .append(LINE_FEED);
    writer.append("Content-Type: text/plain; charset=" + charset).append(
            LINE_FEED);
    writer.append(LINE_FEED);
    writer.append(value).append(LINE_FEED);
    writer.flush();
}

/**
 * Adds a upload file section to the request
 * @param fieldName name attribute in <input type="file" name="..." />
 * @param uploadFile a File to be uploaded
 * @throws IOException
 */
public void addFilePart(String fieldName, File uploadFile) throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
            "Content-Disposition: form-data; name=\"" + fieldName
                    + "\"; filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append(
            "Content-Type: "
                    + URLConnection.guessContentTypeFromName(fileName))
            .append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();
     
    writer.append(LINE_FEED);
    writer.flush();    
}

/**
 * Adds a header field to the request.
 * @param name - name of the header field
 * @param value - value of the header field
 */
public void addHeaderField(String name, String value) {
    writer.append(name + ": " + value).append(LINE_FEED);
    writer.flush();
}
 
/**
 * Completes the request and receives response from the server.
 * @return a list of Strings as response in case the server returned
 * status OK, otherwise an exception is thrown.
 * @throws IOException
 */
public List<String> finish() throws IOException {
    List<String> response = new ArrayList<String>();

    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        System.out.println("Entrato");
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }

    return response;
}}}

Can anybody help me please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

欢你一世 2025-01-16 12:52:59

我刚刚发现在postman中我可以看到调用的java源代码。我用过它,现在它可以工作了。

I just discovered that in postman I can see the java source code of the call. I used that and now it works.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文