I have this method which sends binary data to server. The code works fine, but still, it's structure is kinda stupid: output and input connections are opened like thousands times (depends on data size), closed only once.
I cannot move the code that opens connection outside of the loop because I'm getting strange errors, like the data was never sent to server.
Please help me to restructure this code so it could still work and have a correct structure:
OutputStream os = null;
StringBuffer messagebuffer = new StringBuffer();
HttpURLConnection huc = null;
DataInputStream dis = null;
InputStream in = null;
Path path = null;
byte[] buf = new byte[64 * 1024];
int bytesRead = 0;
try {
path = Paths.get("D:\\testfile.rar");
in = Files.newInputStream(path);
int i = 0;
URL u = new URL(defaultURL);
while ((bytesRead = in.read(buf)) != -1) {
huc = (HttpURLConnection) u.openConnection(); // wrong
huc.setRequestMethod("POST");
huc.setRequestProperty("chunk-number", i + "");
huc.setDoOutput(true); // wrong
huc.setDoInput(true); // wrong
os = huc.getOutputStream(); // wrong
os.write(buf, 0, bytesRead);
os.flush();
System.out.println(i++ + " " + bytesRead);
int ch;
dis = new DataInputStream(huc.getInputStream()); // wrong
long len = huc.getContentLength();
if (len != -1) {
for (int k = 0; k < len; k++)
if ((ch = dis.read()) != -1)
messagebuffer.append((char) ch);
else {
// if the content-length is not available
while ((ch = dis.read()) != -1)
messagebuffer.append((char) ch);
}
}
Thread.sleep(16);
}
dis.close();
huc.disconnect();
int statusCode = huc.getResponseCode();
String message = huc.getResponseMessage();
messagebuffer.append("status code=" + statusCode + "\n");
messagebuffer.append("response message=" + message + "\n");
} catch (Exception ex) {
// throw errors
} finally {
// closing stuff
}
return messagebuffer.toString();
Path
class? \$\endgroup\$