Saltar al contenido

Carga de imagen usando okHttp

Solución:

Necesitas usar

new MultipartBody.Builder()

En lugar de

new MultipartBuilder()

Esta funcionando

Aquí está la clase de solicitud de varias partes.

import java.io.File;
import java.io.IOException;

import org.apache.http.HttpStatus;

import android.content.Context;

import com.esp.ro.util.Config;
import com.esp.ro.util.Log;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;


public class MultipartRequest 

public Context caller;
public MultipartBuilder builder;
private OkHttpClient client;

public MultipartRequest(Context caller) 
    this.caller = caller;
    this.builder = new MultipartBuilder();
    this.builder.type(MultipartBuilder.FORM);
    this.client = new OkHttpClient();


public void addString(String name, String value) 
    this.builder.addFormDataPart(name, value);


public void addFile(String name, String filePath, String fileName) 
    this.builder.addFormDataPart(name, fileName, RequestBody.create(
            MediaType.parse("image/jpeg"), new File(filePath)));


public void addTXTFile(String name, String filePath, String fileName) 
    this.builder.addFormDataPart(name, fileName, RequestBody.create(
            MediaType.parse("text/plain"), new File(filePath)));


public void addZipFile(String name, String filePath, String fileName)

    this.builder.addFormDataPart(name, fileName, RequestBody.create(
           MediaType.parse("application/zip"), new File(filePath)));


public String execute(String url) 
    RequestBody requestBody = null;
    Request request = null;
    Response response = null;

    int code = 200;
    String strResponse = null;

    try 
        requestBody = this.builder.build();
        request = new Request.Builder().header("AUTH-KEY", Config.API_KEY)
                .url(url).post(requestBody).build();

        Log.print("::::::: REQ :: " + request);
        response = client.newCall(request).execute();
        Log.print("::::::: response :: " + response);

        if (!response.isSuccessful())
            throw new IOException();

        code = response.networkResponse().code();

        if (response.isSuccessful()) 
            strResponse = response.body().string();
         else if (code == HttpStatus.SC_NOT_FOUND) 
            // ** "Invalid URL or Server not available, please try again" */
            strResponse = caller.getResources().getString(
                    R.string.error_invalid_URL);
         else if (code == HttpStatus.SC_REQUEST_TIMEOUT) 
            // * "Connection timeout, please try again", */
            strResponse = caller.getResources().getString(
                    R.string.error_timeout);
         else if (code == HttpStatus.SC_SERVICE_UNAVAILABLE) 
            // *
            // "Invalid URL or Server is not responding, please try again",
            // */
            strResponse = caller.getResources().getString(
                    R.string.error_server_not_responding);
        
     catch (Exception e) 
        Log.error("Exception", e);
        Log.print(e);
     finally 
        requestBody = null;
        request = null;
        response = null;
        builder = null;
        if (client != null)
            client = null;
        System.gc();
    
    return strResponse;
  

Espero que esto te ayude.

Nota: Si está usando el antiguo OkHttp que está por debajo de la versión 3, entonces puede usar este método. Si está usando la versión 3 o superior, aquí está la respuesta para usted.

Utilicé de esta manera en OKHTTP 3.4.1

Llamar a una función como esta

if (!realPath.equals("")) 

            new SignupWithImageTask().execute(et_name.getText().toString(), et_email.getText().toString(), et_dob.getText().toString(), IMEI, et_mobile.getText().toString(), realPath);

         else 
            Toast.makeText(this, "Profile Picture not found", Toast.LENGTH_SHORT).show();
        

SignupWithImageTask

  public class SignupWithImageTask extends AsyncTask 

        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() 
            super.onPreExecute();
            progressDialog = new ProgressDialog(SignupActivity.this);
            progressDialog.setMessage("Please Wait....");
            progressDialog.show();
        

        @Override
        protected String doInBackground(String... str)  UnsupportedEncodingException e) 
                Log.e("TAG", "Error: " + e.getLocalizedMessage());
             catch (Exception e) 
                Log.e("TAG", "Other Error: " + e.getLocalizedMessage());
            


            return res;

        

        @Override
        protected void onPostExecute(String response) 
            super.onPostExecute(response);
            if (progressDialog != null)
                progressDialog.dismiss();

            if (response != null) 
                try 

                    JSONObject jsonObject = new JSONObject(response);


                    if (jsonObject.getString("message").equals("success")) 

                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");

                        SharedPreferences settings = getSharedPreferences("preference", 0); // 0 - for private mode
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString("name", jsonObject1.getString("name"));
                        editor.putString("userid", jsonObject1.getString("id"));
                        editor.putBoolean("hasLoggedIn", true);
                        editor.apply();

                        new UploadContactTask().execute();

                        startActivity(new Intent(SignupActivity.this, MainActivity.class));
                     else 
                        Toast.makeText(SignupActivity.this, "" + jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                    
                 catch (JSONException e) 
                    e.printStackTrace();
                
             else 
                Toast.makeText(SignupActivity.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
            

        
    

Eres capaz de confirmar nuestra investigación dejando un comentario y dejando una puntuación te damos la bienvenida.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *