Я использую BasicImageDownloader для загрузки изображения с facebook-графика (могу подтвердить, что 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;
}
Я поступил так, используя этот Вопрос, заданный , и этот Вопрос, заданный