首页 > 解决方案 > Android Java HTTP Post .bin 文件

问题描述

我正在尝试将 .bin 文件从 Android Java 移动应用程序上传到 ESP32 Web 服务器。我知道上传工作正常,因为我可以在网络浏览器上对其进行测试,但是我尝试了 StackOverflow 的不同解决方案,例如 Volley、httpClient 等,但它在传输时崩溃了。

任何关于如何完成文件上传的帮助,看起来都很简单,因为它只是一个 HTTP 后文件传输,但不能让它工作。

http代码

    xhttp.open("POST", upload_path, true);
    xhttp.send(file);

安卓代码

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");
    }
}

=== 更新 ===

我已将代码更新为以下内容,现在出现“java.net.SocketException:连接重置”错误。不确定 contentType 是否需要更改,因为它是使用参考的二进制文件(https://square.github.io/okhttp/3.x/okhttp/index.html?okhttp3/MediaType.html)不知道还有什么它可能需要一个文本文件。

我有一个服务器 500 错误,所以它必须与服务器通信。

   file = new File("/storage/emulated/0/Download/test-1.fw"); 
                filename = "test-1.fw";
                final MediaType contentType = MediaType.parse("text/plain");
                RequestBody requestBody = new MultipartBody.Builder()

                        .setType(MultipartBody.FORM)
                        .addFormDataPart("test-1.fw", filename, RequestBody.create(file,contentType))
                        .build();
                Request request = new Request.Builder()
                        .url("http://10.10.2.0/upload/file.bin")
                        .post(requestBody)
                        .build();

                try (Response response = client.newCall(request).execute()) {
                    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                    System.out.println(response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }

清单文件

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

标签: javascriptandroidhttp

解决方案


拥有异常的堆栈跟踪会很有用,以便确定问题的原因。您可以提供的另一个有用信息是您正在运行的 Android 版本。
Android应用中http失败的可能原因可能是:

  1. 在 Android 清单中缺少 互联网权限?解决方案:在AndroidManifest.xml
    中添加以下语句:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

  2. 您正在使用http协议,但从 Android 9 开始,此协议受到限制
    解决方案 1:使用https协议而不是http
    解决方案 2:在AndroidManifest.xml中添加usesCleartextTraffic属性:

    android:usesCleartextTraffic="true"


推荐阅读