Android:通过发布请求上传图像文件和表单数据始终失败

时间:2018-12-17 23:49:23

标签: java android retrofit2

我正在使用BasicImageDownloader从facebook-graph下载图像(我可以确认URL正常并且文件已下载的事实),然后使用Retrofit发出HTTP发布请求,其中附加了图像文件和一些表格数据。它始终会失败,并且不会在请求的后端打我的API。这是我的代码段。任何建议将不胜感激。 (我已将baseURL的值更改为“ www.example.com”,但如有需要,我可以提供它。)

依赖性:

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'com.google.code.gson:gson:2.8.5'

API接口类

package com.redhen.cuttiin.customerInterface;

import com.teckdk.cuttiin.model.LoggedIn;
import java.util.Map;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.PartMap;
import retrofit2.http.Url;

public interface CustomerApi {
   @Multipart
   @POST("/api/customer/signup")
   Call<ResponseBody> createUser(@Part MultipartBody.Part part,@PartMap 
   Map<String, RequestBody> params);
}

我在哪里进行HTTP发布请求方法

    private void createCustomer(final String email, final String firstName, final String lastName, final String url) {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://teckdkdev.online/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    CustomerApi customerApi = retrofit.create(CustomerApi.class);



    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat mdformat = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss", Locale.US);
    final String strDate = mdformat.format(calendar.getTime());
    final String imageName = UUID.randomUUID().toString();


    BasicImageDownloader basicImageDownloader = new BasicImageDownloader(new BasicImageDownloader.OnImageLoaderListener() {
        @Override
        public void onError(BasicImageDownloader.ImageError error) {
            Log.i("ERROR", "Error code " + error.getErrorCode());

        }

        @Override
        public void onProgressChange(int percent) {

        }

        @Override
        public void onComplete(Bitmap result) {
            final Bitmap.CompressFormat mFormat = Bitmap.CompressFormat.JPEG;
            final File myImageFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
                    File.separator + "image_test" + File.separator + imageName + "." + mFormat.name().toLowerCase());

            HashMap<String, RequestBody> params = new HashMap<>();
            params.put("firstName", toRequestBody(firstName));
            params.put("lastName", toRequestBody(lastName));
            params.put("email", toRequestBody(email));
            params.put("profileImageName", toRequestBody(imageName));
            params.put("password", toRequestBody("not available"));
            params.put("dateCreated", toRequestBody(strDate));
            params.put("dateCreatedTimezone", toRequestBody(userTimezone));
            params.put("dateCreatedCalendar", toRequestBody(userCalendar));
            params.put("dateCreatedLocale", toRequestBody(userLocale));
            params.put("authenticationType", toRequestBody("facebook"));
            params.put("role", toRequestBody("customer"));
            params.put("barberShopOwner", toRequestBody("NO"));
            params.put("accountDeactivated", toRequestBody("NO"));

            RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), myImageFile);
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", myImageFile.getName(), requestBody);

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://example.com/")
                    .build();

            CustomerApi customerApi = retrofit.create(CustomerApi.class);
            customerApi.createUser(part, params).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                    try {

                        Log.d("response data", "message" + response.body().string());
                        System.out.println(response);
                    }catch (Exception e) {
                        e.printStackTrace();
                        System.out.println(response);
                    }

                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Log.i("error occured", "something died");
                    System.out.println(call.request().toString());

                }
            });
        }
    });

    basicImageDownloader.download(url, true);
}

public RequestBody toRequestBody(String value) {
    RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
    return body;
}

我开始使用这个Question asked和这个Question asked

0 个答案:

没有答案