代码之家  ›  专栏  ›  技术社区  ›  Pavel Sumarokov

如何使用改装将图像从内部存储上载到服务器?

  •  0
  • Pavel Sumarokov  · 技术社区  · 7 年前

    我正在尝试将两张图像从android设备的内部存储上传到HTTP服务器。

        public interface ApiService {
            ...
    
            @Multipart
            @Headers("Content-Type: application/json")
            @POST("signature/{id}")
            Call<String> sendSignature(
                    @Header("Authorization") String authorization,
                    @Path("id") String id,
                    @Part("descrtipion") RequestBody description,
                    @Part MultipartBody.Part file1,
                    @Part MultipartBody.Part file2);
        }
    
    ...
    
    
    private void sendSignatures(){
        RequestBody description = RequestBody.create(okhttp3.MultipartBody.FORM, getString(R.string.str_file_description));
    
        File file2 = getFileStreamPath(SIGNATURE2_PATH);
        RequestBody requestFile2 = RequestBody.create(MediaType.parse("image/png"), file2);
        MultipartBody.Part body2 = MultipartBody.Part.createFormData("sign1", file2.getName(), requestFile2);
    
        File file = getFileStreamPath(SIGNATURE_PATH);
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("sign2", file.getName(), requestFile);
    
        Call<String> call = ApiFactory.getService().sendSignature(token, PARAMETER_ID, description, body2, body);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful()) Log.d("myLogs", "Yes: " + response.body());
                else Toast.makeText(MainActivity.this, ErrorUtils.errorMessage(response), Toast.LENGTH_LONG).show();
            }
    
            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Toast.makeText(MainActivity.this, t.toString(), Toast.LENGTH_LONG).show();
            }
        });
    }
    

    但服务器返回错误#500。同时,邮递员的请求成功(#200)。

    请帮助我解决这个问题:我在java代码中哪里会出错?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Pavel Sumarokov    7 年前

    我找到了解决办法。特别是在这种情况下,有必要拆下收割台:

    public interface ApiService {
        ...
    
        @Multipart
        @POST("signature/{id}")
        Call<String> sendSignature(
                @Header("Authorization") String authorization,
                @Path("id") String id,
                @Part("descrtipion") RequestBody description,
                @Part MultipartBody.Part file1,
                @Part MultipartBody.Part file2);
    }
    

    当我试图通过邮递员发送此请求时,只放了一个或两个文件,其中一个或两个都有错误的密钥,即使令牌不正确,服务器也传递了#500错误。所以首先他们检查密钥和文件,然后-授权参数。我删除了标题,在这种情况下得到了成功的响应。