I am using multipart/form-data to send a POST request. I used a file that has the data stored as a csv.The file is person,positon,id. I am concerned that the error could be not having the correct writer like Dataoutput stream vs outputstream. The way I have the carriage returns and line feeds setup or any of my connection settings are off. The URL is correct but the last parameter asks for a file name and I put that in content-dispostion. I can't get rid of this error with all the changes I make. I just want to know if anything on this is incorrect. I get back a 500 error but that leads to the received this error:
org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.impl.IOFileUploadException: Processing of multipart/form-data request failed. Stream ended unexpectedly
Any advice or changes would be appreciated.
public static String postFile(String url) throws IOException {
String boundary = "xxxxxxxxxxxxxxxxxxxxxxxxx";
String charset = "UTF-8";
String CRLF = "\r\n";
int boundaryLength = 181;
try {
BufferedReader in = null;
File userss = new File("bytesExampleCSV.csv");
URL obj = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Mobile Safari/537.36");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Content-Length", String.valueOf((userss.length()) + boundaryLength));
conn.connect();
OutputStream output = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
try {
writer.append("--").append(boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"bytesExampleCSV.csv\"; filename=\""
+ userss.getName() + "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).flush();
Files.copy(userss, output);
output.flush();
// writer.append(CRLF);
writer.append("--" + boundary + "--").append(CRLF).flush();
writer.close();
conn.disconnect();
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}