0

I need to post a file to the server along with other fields to a webapi. This is the code that I've implemented but it doesn't seem to work.

FileInputStream fileStream = new FileInputStream(file);
b = new byte[(int)file.length()];
fileStream.read(b);
fileName = file.getName();
String crlf = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";

URL url = new URL(URL);
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches( false );
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

DataOutputStream wr = new DataOutputStream( connection.getOutputStream());
wr.writeBytes(twoHyphens+boundary+crlf);
wr.writeBytes("Content-Disposition: form-data; process=\"extractText\";user=\"" + username + "\";pass=\"" + password + "\";filename=\"" + file.getName() + "\";file=\"");
wr.write(b);
wr.writeBytes("\"" + crlf);
wr.writeBytes(crlf);
wr.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
wr.flush();
wr.close();

responseStream  = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(responseStream);
strBuff = new StringBuffer();
String s;
while ( ( s = br.readLine() ) != null ) {
    strBuff.append(s);
}
br.close();
responseStream.close();
connection.disconnect();
str = strBuff.toString();
data = str;
parser = new JSONParser();
jsonObj = (JSONObject)parser.parse(str);
str = jsonObj.get("status").toString();

None of the data gets posted. Please help.

1 Answers1

0

I'd suggest using an Http client implementation.

for example, this one shows how to do it with Jersey client: https://stackoverflow.com/a/24647315/3356136

you can also consider other implementations like Apache HttpComponents

Community
  • 1
  • 1