问题
Hi friends please help me out here i am new for the retrofit i am trying use the post method in the retrofit to send the image file by converting it into base64 format but it is not uploading please friends help me out this is my code
Retrofit code
Retrofit registerretrofit = new Retrofit.Builder().baseUrl(Constant.url).client(Constant.okClient()).addConverterFactory(GsonConverterFactory.create()).build();
Api registerapi = registerretrofit.create(Api.class);
String urlbitmap=Constant.getStringImage(profilebitmap);
Call<LoginResponse> registerresponse = registerapi.getregisterdetails(namestring, emailstring, passwordstring, phonestring, citystring, landnumstring, housenumstring, adrsstring1, adrssrtring2,urlbitmap, "Android", "DeviceToken", lat, lngitude);
registerresponse.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
// Constant.l(Constant.getStringImage(profilebitmap));
try {
Constant.l(String.valueOf(response));
} catch (Exception e) {
Constant.l(e.toString());
}
/*Constant.l(String.valueOf(response));
if (response.body().getStatus().equals("success")) {
Session.createlogin(getApplicationContext(), response.body().getUserid(), response.body().getName(), response.body().getEmail());
Intent loginintent = new Intent(getApplicationContext(), Login.class);
loginintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginintent);
} else if (response.body().getStatus().equals("failure")) {
Constant.s(username, "Email Already Exists");
}*/
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Constant.l(t.toString());
}
});
}
Interface.java
@FormUrlEncoded
@POST("keemajson.php?action=register")
Call<LoginResponse> getregisterdetails(@Query("uname") String uname, @Query("email") String email, @Query("password") String password, @Query("phone") String phone, @Query("city") String city, @Query("landline") String landline, @Query("building_num") String building_num, @Query("address1") String address1, @Query("address2") String address2, @Field("image") String image, @Query("device_name") String device_name, @Query("device_token") String device_token, @Query("lat") String lat, @Query("lng") String lng);
Base64 Method
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imagebytes = baos.toByteArray();
String uploadencodedImage = Base64.encodeToString(imagebytes, Base64.DEFAULT);
The Reponse i am getting is
Response{protocol=http/1.0, code=500, message=Internal Server Error, url=http://54.202.3.127/keema/keemajson.php?action=register&uname=test2&email=tester2@gmail.com&password=123456&phone=1234567890&city=KKD&landline=0884237688&building_num=12-2-18&address1=Address1&address2=Address2&device_name=Android&device_token=DeviceToken&lat=16.9952685&lng=82.2450855}
This multipart code i had used
Retrofit registerretrofit = new Retrofit.Builder().baseUrl("http://54.202.3.127/keema/").client(Constant.okClient()).addConverterFactory(GsonConverterFactory.create()).build();
Api registerapi = registerretrofit.create(Api.class);
File profilefile = new File("/storage/emulated/0/Pictures/Screenshots/Screenshot_2017-02-22-14-10-53.png");
RequestBody reqfile = RequestBody.create(MediaType.parse("image/*"), profilefile);
RequestBody actionrb = RequestBody.create(MediaType.parse("text/plain"), "register");
MultipartBody.Part body = MultipartBody.Part.createFormData("image", profilefile.getName(), reqfile);
RequestBody namerb = RequestBody.create(MediaType.parse("text/plain"), namestring);
RequestBody emailrb = RequestBody.create(MediaType.parse("text/plain"), emailstring);
RequestBody passwordrb = RequestBody.create(MediaType.parse("text/plain"), passwordstring);
RequestBody phonerb = RequestBody.create(MediaType.parse("text/plain"), phonestring);
RequestBody cityrb = RequestBody.create(MediaType.parse("text/plain"), citystring);
RequestBody adrssrb = RequestBody.create(MediaType.parse("text/plain"), adrsstring1);
RequestBody adrssrrb = RequestBody.create(MediaType.parse("text/plain"), adrssrtring2);
RequestBody landnumrb = RequestBody.create(MediaType.parse("text/plain"), landnumstring);
RequestBody housenumrb = RequestBody.create(MediaType.parse("text/plain"), housenumstring);
RequestBody devicenamerb = RequestBody.create(MediaType.parse("text/plain"), "Android");
RequestBody devicetokenrb = RequestBody.create(MediaType.parse("text/plain"), "Devicetoken");
RequestBody latrb = RequestBody.create(MediaType.parse("text/plain"), lat);
RequestBody lngrb = RequestBody.create(MediaType.parse("text/plain"), lngitude);
Call<ResponseBody> respbody = registerapi.getregisterdetails(actionrb,body, namerb, emailrb, passwordrb, phonerb, cityrb, adrssrb, adrssrrb, landnumrb, housenumrb, devicenamerb, devicetokenrb, latrb, lngrb);
respbody.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Constant.l(String.valueOf(response));
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Constant.l(t.toString());
}
});
}
Interface of Multipart
@Multipart
@POST("keemajson.php")
Call<ResponseBody> getregisterdetails(@Part("action") RequestBody action,@Part MultipartBody.Part image,@Part("uname") RequestBody uname, @Part("email") RequestBody email, @Part("password") RequestBody password, @Part("phone") RequestBody phone, @Part("city") RequestBody city, @Part("landline") RequestBody landline, @Part("building_num") RequestBody building_num, @Part("address1") RequestBody address1, @Part("address2") RequestBody address2, @Part("device_name") RequestBody device_name, @Part("device_token") RequestBody device_token, @Part("lat") RequestBody lat, @Part("lng") RequestBody lng);
回答1:
In order to POST a file, we need to enable Multipart
.Part
define a part inside the Multipart
. MultipartBody.Part
is the type that we want to use for a file / image. Non-file Part should use RequestBody
type with expected fieldname
Service / Endpoint interface
interface Service {
@Multipart
@POST("/")
Call<ResponseBody> postImage(@Part MultipartBody.Part image, @Part("name") RequestBody name);
}
Retrofit call, postImage parameter
File file = new File(filePath);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");
retrofit2.Call<okhttp3.ResponseBody> req = service.postImage(body, name);
req.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
// Do Something
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
Go through this githib example for more details
EDIT
Parameters along with Image would be as follows
@Multipart
@POST("users/{id}/user_photos")
Call<models.UploadResponse> postImage(@Path("id") int userId, @PartMap Map<String, RequestBody> params);
Request parameters
//All the String parameters
Map<String, RequestBody> map = new HashMap<>();
map.put("methodName", toRequestBody(methodName));
map.put("userid", toRequestBody(userId));
map.put("name", toRequestBody(name));
//To put your image file as well
File file = new File("file_name");
RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);
map.put("relative_image\"; filename=\"some_file_name.png\"", fileBody);
// This method converts String to RequestBody
public static RequestBody toRequestBody (String value) {
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
return body ;
}
//To send your request
call = service.postImage(body, params);
回答2:
May be you need to form-encoded-url?
来源:https://stackoverflow.com/questions/42578764/image-file-not-going-to-server-using-retrofit-2-post-method