Research has made it necessary to POST images from Android to PHP on Azure It seems to be fun to use without thinking about asynchronous processing! !! I adopted Retrofit 2 because of the short-circuit thinking, but I was addicted to it unexpectedly, so a memo
--The following code is written on the assumption that it will be POSTed to http://example.com/upload/index.php --Permissions such as network access and access to internal storage are assumed to be given.
--Add the following sentence at the bottom of the familiar app / build.gradle
app/build.gradle
dependencies {
:
:
compile 'com.squareup.retrofit2:retrofit:2.1.0+'
}
--Since the base URL is specified separately, Path is relative and OK
UploadService.class
public interface UploadService {
@Multipart
//Path can be the one without the base URL
@POST("upload/index.php")
Call<ResponseBody> upload(@Part MultipartBody.Part file);
}
ServiceGenerator -Quoted from Official -** Only the base URL part needs to be rewritten **
ServiceGenerator.class
public class ServiceGenerator {
//Specify the base URL here
public static final String API_BASE_URL = "http://example.com/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(API_BASE_URL);
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
}
UploagService service = ServiceGenerator.createService(UploadService.class);
//Files such as images, music, videos, etc. to be POSTed
String filePath = ”path/to/your/file”;
File file = new File(filePath);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("POST destination field name", file.getName(), requestFile);
Call<ResponseBody> call = service.upload(body);
call.enqueue(new Callback<ResponseBody>() {
//Called when the status code is other than an error code such as 400
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//Processing on success
// response.body();You can get inside the body tag of the HTML response with
}
//Called when the status code is an error code such as 400
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
//Processing at the time of failure
}
});
Recommended Posts