POST Multipart Form Data using Retrofit 2.0 including image

前端 未结 10 1600
名媛妹妹
名媛妹妹 2020-11-22 11:07

I am trying to do a HTTP POST to server using Retrofit 2.0

MediaType MEDIA_TYPE_TEXT = MediaType.parse(\"text/plain\");
MediaType MEDIA_TYPE         


        
10条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 11:51

    I used Retrofit 2.0 for my register users, send multipart/form File image and text from register account

    In my RegisterActivity, use an AsyncTask

    //AsyncTask
    private class Register extends AsyncTask {
    
        @Override
        protected void onPreExecute() {..}
    
        @Override
        protected String doInBackground(String... params) {
            new com.tequilasoft.mesasderegalos.dbo.Register().register(txtNombres, selectedImagePath, txtEmail, txtPassword);
            responseMensaje = StaticValues.mensaje ;
            mensajeCodigo = StaticValues.mensajeCodigo;
            return String.valueOf(StaticValues.code);
        }
    
        @Override
        protected void onPostExecute(String codeResult) {..}
    

    And in my Register.java class is where use Retrofit with synchronous call

    import android.util.Log;
    import com.tequilasoft.mesasderegalos.interfaces.RegisterService;
    import com.tequilasoft.mesasderegalos.utils.StaticValues;
    import com.tequilasoft.mesasderegalos.utils.Utilities;
    import java.io.File;
    import okhttp3.MediaType;
    import okhttp3.MultipartBody;
    import okhttp3.RequestBody;
    import okhttp3.ResponseBody;
    import retrofit2.Call; 
    import retrofit2.Response;
    /**Created by sam on 2/09/16.*/
    public class Register {
    
    public void register(String nombres, String selectedImagePath, String email, String password){
    
        try {
            // create upload service client
            RegisterService service = ServiceGenerator.createUser(RegisterService.class);
    
            // add another part within the multipart request
            RequestBody requestEmail =
                    RequestBody.create(
                            MediaType.parse("multipart/form-data"), email);
            // add another part within the multipart request
            RequestBody requestPassword =
                    RequestBody.create(
                            MediaType.parse("multipart/form-data"), password);
            // add another part within the multipart request
            RequestBody requestNombres =
                    RequestBody.create(
                            MediaType.parse("multipart/form-data"), nombres);
    
            MultipartBody.Part imagenPerfil = null;
            if(selectedImagePath!=null){
                File file = new File(selectedImagePath);
                Log.i("Register","Nombre del archivo "+file.getName());
                // create RequestBody instance from file
                RequestBody requestFile =
                        RequestBody.create(MediaType.parse("multipart/form-data"), file);
                // MultipartBody.Part is used to send also the actual file name
                imagenPerfil = MultipartBody.Part.createFormData("imagenPerfil", file.getName(), requestFile);
            }
    
            // finally, execute the request
            Call call = service.registerUser(imagenPerfil, requestEmail,requestPassword,requestNombres);
            Response bodyResponse = call.execute();
            StaticValues.code  = bodyResponse.code();
            StaticValues.mensaje  = bodyResponse.message();
            ResponseBody errorBody = bodyResponse.errorBody();
            StaticValues.mensajeCodigo  = errorBody==null
                    ?null
                    :Utilities.mensajeCodigoDeLaRespuestaJSON(bodyResponse.errorBody().byteStream());
            Log.i("Register","Code "+StaticValues.code);
            Log.i("Register","mensaje "+StaticValues.mensaje);
            Log.i("Register","mensajeCodigo "+StaticValues.mensaje);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
    }
    

    In the interface of RegisterService

    public interface RegisterService {
    @Multipart
    @POST(StaticValues.REGISTER)
    Call registerUser(@Part MultipartBody.Part image,
                                    @Part("email") RequestBody email,
                                    @Part("password") RequestBody password,
                                    @Part("nombre") RequestBody nombre
    );
    }
    

    For the Utilities parse ofr InputStream response

    public class Utilities {
    public static String mensajeCodigoDeLaRespuestaJSON(InputStream inputStream){
        String mensajeCodigo = null;
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(
                        inputStream, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            inputStream.close();
            mensajeCodigo = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        return mensajeCodigo;
    }
    }
    

提交回复
热议问题