【问题标题】:Upload a file in Android在 Android 中上传文件
【发布时间】:2016-04-13 07:18:08
【问题描述】:

在 Android 中,如何将二进制文件上传到服务器似乎非常令人困惑,因为一些库已经过时,并且缺乏现在应该使用哪种方法的信息。 谁能指点一下如何将二进制文件或任何文件上传到 Android 中的服务器?

我宁愿不使用任何依赖项,除非它们确实是必要的。

【问题讨论】:

  • 尝试改造它对任何类型的服务器交互都非常有帮助!

标签: java android


【解决方案1】:

由于缺乏信息,这可能是哪种服务器,我找到了this

OkHttpClient client = new OkHttpClient();
OutputStream out = null;
try {
    URL url = new URL("http://www.example.com");
    HttpURLConnection connection = client.open(url);
    for (Map.Entry<String, String> entry : multipart.getHeaders().entrySet()) {
        connection.addRequestProperty(entry.getKey(), entry.getValue());
    }
    connection.setRequestMethod("POST");
    // Write the request.
    out = connection.getOutputStream();
    multipart.writeBodyTo(out);
    out.close();

    // Read the response.
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new IOException("Unexpected HTTP response: "
                + connection.getResponseCode() + " " + connection.getResponseMessage());
    }
} 
finally {
    try { if (out != null) out.close(); } 
    catch (Exception e) {}
}

我假设您提到的已弃用/过时的库是ApacheHttpClient,因此我推荐OkHttp(我相信使用HttpUrlConnection)。

要将 OkHttp 添加为依赖项,您可以编辑您的 build.gradle,如下所示:

dependencies {
    //some other dependencies
    compile 'com.squareup.okhttp:okhttp:2.7.2'
}

可用版本在这里:mvnrepository(无需手动下载,只需像上面一样添加它们,gradle会自行下载)

【讨论】:

  • 我应该使用哪些依赖项以及如何添加它们?
  • 嘿,“客户端”似乎没有名为“open()”的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-28
  • 2012-03-28
相关资源
最近更新 更多