Android Java HTTP Post .bin file
Budget: £36 – £0 GBP
I am trying to upload a .bin file from an Android Java mobile app to an ESP32 web server. I know the upload is working as I can test it on a web browser, but I have tried different solutions from StackOverflow such Volley, httpClient etc but it crashes on the transfer.
Any help how to complete the file upload, looks quite simple as it's just an HTTP post file transfer, I need working code. I do not need any app developing, just some working java code.
http code
xhttp.open("POST", upload_path, true);
xhttp.send(file);
Android java code
public void uploadfile() throws Exception
{
try {
File file = new File("/storage/emulated/0/Download/testfile.bin");
if (file.exists()) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("http://10.10.10.1/upload/");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// builder.addTextBody("field1", "yes", ContentType.DEFAULT_BINARY);
// This attaches the file to the POST:
File f = new File("/storage/emulated/0/Download/testfile.bin");
builder.addBinaryBody(
"file",
new FileInputStream(f),
ContentType.DEFAULT_BINARY,
f.getName()
);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
// Code is crashing here
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
}
}
catch (Exception e)
{
Log.d("Debug", "Catch - software activity 1050");
}
}
Any help how to complete the file upload, looks quite simple as it's just an HTTP post file transfer, I need working code. I do not need any app developing, just some working java code.
http code
xhttp.open("POST", upload_path, true);
xhttp.send(file);
Android java code
public void uploadfile() throws Exception
{
try {
File file = new File("/storage/emulated/0/Download/testfile.bin");
if (file.exists()) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("http://10.10.10.1/upload/");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// builder.addTextBody("field1", "yes", ContentType.DEFAULT_BINARY);
// This attaches the file to the POST:
File f = new File("/storage/emulated/0/Download/testfile.bin");
builder.addBinaryBody(
"file",
new FileInputStream(f),
ContentType.DEFAULT_BINARY,
f.getName()
);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
// Code is crashing here
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
}
}
catch (Exception e)
{
Log.d("Debug", "Catch - software activity 1050");
}
}
Related categories:
Business, Accounting, Human Resources & Legal
JavaScript
Mobile App Development
Android
HTTP