有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android:通过post请求上传图像文件和表单数据总是失败

我正在使用BasicImageDownloader从facebook graph下载图像(我可以确认URL是否有效,文件是否已下载),然后使用Reformation发出HTTP post请求,其中我附加了图像文件和一些表单数据。它总是失败,并且不会在请求的后端命中我的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 post请求方法

    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;
}

我是用这个{a1}和这个{a2}这样做的


共 (0) 个答案