Hi I am working on a normal Java project "A",I need to access this API having end-point "rest/documents/upload" from project "S" which is a Sping boot project.This api has its inputs like this-enter image description here
I have to pass in a pdf file as form data,the key is "files" and the value is the pdf file(as in Postman),the parent value is the query param(2149 in my case), and an auth token in the header.This returns me an response something like-
{"entity":[key:value,key:value.....],"status":200,"message":null}
In order to do this,I am trying to use "httpURLConnection" in my project "A" to call the API in project "S".Here is the code I have written to do this-
URL url = new URL(postTarget);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String oauthToken="Bearer xxxxauthTokenxxxx";
String auth = "Bearer " + oauthToken;
connection.setRequestProperty("Authorization", auth);
String boundary = UUID.randomUUID().toString();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
String charset = "UTF-8";
String param = "value";
String CRLF = "\r\n";
//Send text file.
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"pdfFile\"; filename=\"" + listOfFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
writer.append(CRLF).flush();
Files.copy(listOfFile.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 respCode = connection.getResponseCode();
System.out.println("respCode = " + respCode);
BufferedReader in=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response=new StringBuffer();
while((inputLine=in.readLine()) !=null)
{
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
I am getting the response as 200,but the problem I am facing is the entity class is returning empty ie without the key-value pairs.like this-
{"entity":[],"status":200,"message":null}
I am trying to do what i got from here-here
Upload files from Java client to a HTTP server
Can you say where I am going wrong?Any help appreciated.