【问题标题】:POST with httpurlconnection: a better way?使用 httpurlconnection 发布:更好的方法?
【发布时间】:2015-05-22 16:14:52
【问题描述】:

Android 现在建议对 http 请求使用 HttpUrlConnection。

但是,似乎没有一种发布文件的好方法。使用旧的 HttpClient 库,它非常简单 (How do I send a file in Android from a mobile device to server using http?)

但是,这似乎是我能为 HttpUrlConnection Sending files using POST with HttpURLConnection 找到的最佳解决方案

虽然该解决方案有效,但要解决一个真正常见的问题,需要进行大量的改造。我觉得必须有更好的方法。我似乎无法找到它。

【问题讨论】:

    标签: android http post


    【解决方案1】:

    这可能与您正在寻找的有点不同(因为它不直接使用 httpurlconnection),但如果您准备进行一些更改,或者它仍处于开发过程的早期(或者即使你不是),我建议你研究一下 Retrofit 来处理你所有的网络问题:http://square.github.io/retrofit/

    如果你想这样做,你可以这样做:https://futurestud.io/blog/retrofit-how-to-upload-files/

    我在自己的工作中做过类似的事情,但不能真正分享,所以我将从那篇文章中复制选定的部分代码。如您所见,这非常简单。

    服务:

    @Multipart
    @POST("/upload")
    void upload(@Part("myfile") TypedFile file,
                @Part("description") String description,
                Callback<String> cb);
    

    提出请求:

    FileUpload Service service = ServiceGenerator.createService(FileUpload.class, FileUpload.BASE_URL);
    TypedFile typedFile = new TypedFile("multipart/form-data", new File("path/to/your/file"));
    String description = "hello, this is description speaking";
    service.upload(typedFile, description, new Callback<String>() {
        @Override
        public void success(String s, Response response) {
            Log.e("Upload", "success");
        }
    
        @Override
        public void failure(RetrofitError error) {
            Log.e("Upload", "error");
        }
    });
    

    再次,抱歉,如果这不能解决您的具体问题,但我认为它确实解决了您的“重新发明轮子以解决一个真正常见的问题”部分。

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      相关资源
      最近更新 更多