【问题标题】:POST request with Multipart File and parameters in Java带有多部分文件和 Java 参数的 POST 请求
【发布时间】:2023-01-23 15:55:18
【问题描述】:

我有POST API endpoint爪哇,如下所示,将在门户中为 storing student marksheet 调用。

POST API endpoint

/**
@param name
        Name of student
@param class
        Class of student
@param section
        Section of student
@param rollno
        Roll Number of student
@param file
        Marksheet of student in .xlsx format
**/
@PostMapping(value="/storeMarksheet", produces = "application/json")
public String performTaskAndSendResponse(
    @RequestParam String name,
    @RequestParam String class,
    @RequestParam String section,
    @RequestParam String rollno,
    @RequestPart(name=file) @ApiParam(".xlsx file") MultipartFile file
){
    System.out.println("Inside store marksheet endpoint") // not getting printed
    // Store marksheet and return response accordingly
}

并编写了一个如下所示的函数来调用它

POST API function call

public String postAPI(String name, String class, String section, String rollno, MultipartFile marksheet){
    Map<String, Object> student = new HashMap<String, Object>;
    student.put("name", name);
    student.put("class", class);
    student.put("section", section);
    student.put("rollno", rollno);
    student.put("file", marksheet);

    String dataAsString = student.toString();
    String API = "https://somedomain.com/example/storeMarksheet";
    StringBuilder resp = new StringBuilder();
    String lineResponse = null;

    try{
        URL url = new URL(API);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Using HttpURL connection
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        dos.write(dataAsString.getBytes("utf-8"));
        
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
        while((lineResponse = br.readLine()) != null) resp.append(lineResponse.trim());

        System.out.println(resp.toString());
        return resp;
    }catch(Exception e){
        return null;
    }

}

但是似乎这个电话是not going根本。 使用HttpURL连接用于进行 http 调用。

NOTE

  1. 如果不可能,第一优先级是仅通过HttpURLConnection发送 然后打开其他解决方案
  2. 上面的 POST API 端点在 swagger 中完美运行。

【问题讨论】:

  • 是什么让您认为 student.toString 是将数据作为请求正文发送的正确方式?它不是。我还强烈建议使用其他东西(比如 RestTemplateWebClient 来发送请求,因为你已经在使用 Spring)。
  • 能否请您发布一个答案....我对事物持开放态度,只是我主要使用字符串来完成这就是为什么认为这种方式是可能的。请帮忙
  • 任何人都可以帮忙吗?我正在尝试并需要解决方案

标签: java spring http post httpurlconnection


【解决方案1】:

试图通过 HttpURLConnection 来做,但对我没有任何作用。因此使用另一个过程发布答案

public String postAPI(String name, String class, String section, String rollno, MultipartFile marksheet){
    String responseStr = null;
    try{
        HttpPost req = new HttpPost("https://somedomain.com/example/storeMarksheet");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("name",name);
        builder.addTextBody("class",class);
        builder.addTextBody("section",section);
        builder.addTextBody("rollno",rollno);
        builder.addbinaryBody("file", marksheet.getBytes(), ContentType.DEFAULT_BINARY, marksheet.getOriginalFilename() );
    
        HttpEntity entity = builder.build();
        req.setEntity(entity);
        CloseableHttpClient client = HttpClientBuilder.create().build();
        CloseableHttpResponse res = client.execute(req);
        responseStr = EntityUtils.toString(res.getEnity().toString());
        System.out.println(responseStr); 
    }catch(Exception e){
        //do something.. have put common exception for now
        
    }finally{
        try{
            res.close();
            client.close();
        }catch(Exception e){
            //do something.. have put common exception for now
        }
        return responseStr;
    }
}

【讨论】:

    猜你喜欢
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2017-01-04
    • 1970-01-01
    • 2015-11-26
    • 2017-09-30
    • 1970-01-01
    相关资源
    最近更新 更多