【发布时间】: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
- 如果不可能,第一优先级是仅通过
HttpURLConnection发送 然后打开其他解决方案 - 上面的 POST API 端点在 swagger 中完美运行。
【问题讨论】:
-
是什么让您认为
student.toString是将数据作为请求正文发送的正确方式?它不是。我还强烈建议使用其他东西(比如RestTemplate或WebClient来发送请求,因为你已经在使用 Spring)。 -
能否请您发布一个答案....我对事物持开放态度,只是我主要使用字符串来完成这就是为什么认为这种方式是可能的。请帮忙
-
任何人都可以帮忙吗?我正在尝试并需要解决方案
标签: java spring http post httpurlconnection