代码之家  ›  专栏  ›  技术社区  ›  Hard Developer

带有Android Retrofit 2.X的Rails回形针宝石不工作

  •  1
  • Hard Developer  · 技术社区  · 10 年前

    我正在创建rails后端以从浏览器上传图像&移动客户端(Android)使用回形针宝石。它可以与所有web浏览器、移动浏览器以及HTTP REST客户端工具配合使用,但不能与带有改进HTTP库的android客户端配合使用。这两者兼容吗

    1 回复  |  直到 10 年前
        1
  •  3
  •   andrey2ag    10 年前

    答案是肯定的 使其工作并不容易,但是,

    我是这样做的…这对我很有用

    接口声明

    public interface MultimediaApi {
    
    @Multipart
    @POST("api/v1/multimedia")
    Call<ResponseBody> uploadMultimedia(@Part("tipo]") String tipo,
                                   @Part("archivo\"; filename=\"myimageName\" ") RequestBody archivo, // archivo is the how we named the field of the file in rails server
    // see filename=\"myimageName\" does not have file extension to avoid problems with paperclip content types validations
                                   @Part("texto") String texto,
                                   @Part("acoplable_id") String acoplable_id,
                                   @Part("acoplable_type") String acoplable_type
                                  );
    }
    

    执行时线程

    Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RestConnection.BASE_URL_MULTIMEDIA)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
    
        MultimediaApi apiService =
                retrofit.create(MultimediaApi.class);
    
        Call<ResponseBody> call;
        MediaType MEDIA_TYPE = MediaType.parse("image/jpeg");
        File file = new File(filePath);
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE, file);
    
        call = apiService.uploadMultimedia(
                            type.toString(),
                            requestBody,
                            text.toString(),
                            acopable_id.toString(),
                            acopable_type.toString()
                    );
    
        Response<ResponseBody> response = call.execute();
    
    
            int statusCode = response.code();
            if (statusCode == 201) {
                // Server response OK            
            } else {
               //failed
                    Throwable th = new Throwable("Status Code:" + statusCode + " Error uploading image... Response: " + response.body());
                    return th;
                }
    

    这些例子对我帮助很大,为了解决我的问题,我只是做了一些修改,使其正常工作,所以要仔细查看每个细节

    https://guides.codepath.com/android/Consuming-APIs-with-Retrofit

    https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server

    /**Pura Vida**/