我正在将应用程序升级到 API 23,其中org.apache.http
已弃用。
我当前(已弃用)的代码如下所示:
HttpClient httpClient = new DefaultHttpClient();
File file = new File(attr.Value);
String url = server_url;
HttpPost request = new HttpPost(url);
FileEntity fileEntity = new FileEntity(file, "image/png");
request.setEntity(fileEntity);
HttpResponse response = httpClient.execute(request);
String output = getContent(response.getEntity().getContent());
我发现了一些关于如何使用以下方法完成此操作的建议HttpURLConnection
,但它们都比当前的解决方案复杂得多(不能再使用)。我正在讨论用于执行与上述相同功能的多行代码。
例子有:这一页 http://www.28im.com/android/a181764.html and 这一页 https://stackoverflow.com/questions/11766878/sending-files-using-post-with-httpurlconnection
有没有人有一个好的可靠的较短的解决方案?
如果你改变你的compileSdkVersion
到 21,您的应用程序将干净地编译。话虽如此,Google 放弃内置 HttpClient 实现是有原因的,因此您可能应该寻求其他一些库。那
“其他一些图书馆”可能是:
- 内置经典Java
HttpUrlConnection
,尽管正如您所发现的,它的 API 仍有一些不足之处
- Apache的独立包装适用于 Android 的 HttpClient https://hc.apache.org/httpcomponents-client-4.3.x/android-port.html
-
OkHttp http://square.github.io/okhttp/(我的推荐)
- Android异步 https://github.com/koush/AndroidAsync
特别是,OkHttp 似乎有一个非常好的 API发布文件 https://github.com/square/okhttp/wiki/Recipes#posting-a-file and 发布多部分表单 https://github.com/square/okhttp/wiki/Recipes#posting-a-multipart-request,这应该与您的 HttpClient 代码正在执行的操作类似。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)