2015-08-28 20 views
13

Ho già una classe secondaria di richiesta che viene utilizzato per HTTP Post al server. Il problema è che non ho idea di come posso aggiungere un parametro per un file. Pubblicare una stringa sul server è facile. ma ho bisogno di aggiungere il file come parametro diverso. Come posso farlo?Come caricare file utilizzando la libreria Volley in Android?

public class AddNewPetRequest extends Request<JSONObject> { 

    private Response.Listener<JSONObject> listener; 

    public AddNewPetRequest(String url, Map<String, String> params, 
           Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) { 
     super(Request.Method.GET, url, errorListener); 
     this.listener = reponseListener; 
     this.params = params; 
    } 

    public AddNewPetRequest(int method, String url, Map<String, String> params, 
           Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) { 
     super(method, url, errorListener); 
     this.listener = reponseListener; 
     this.params = params; 
    } 

    protected Map<String, String> getParams() 
      throws com.android.volley.AuthFailureError { 
     return params; 
    }; 

    @Override 
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { 
     try { 
      String jsonString = new String(response.data, 
        HttpHeaderParser.parseCharset(response.headers)); 
      return Response.success(new JSONObject(jsonString), 
        HttpHeaderParser.parseCacheHeaders(response)); 
     } catch (UnsupportedEncodingException e) { 
      return Response.error(new ParseError(e)); 
     } catch (JSONException je) { 
      return Response.error(new ParseError(je)); 
     } 
    } 

    @Override 
    protected void deliverResponse(JSONObject response) { 
     // TODO Auto-generated method stub 
     listener.onResponse(response); 
    } 
} 

UPDATE DOMANDA: seguo il modello di una delle risposte qui a StackOverflow e mi si avvicinò con questa implementazione:

public class MultipartRequest extends Request<String> { 

private MultipartEntity entity = new MultipartEntity(); 

private final Response.Listener<String> mListener; 
private HashMap<String, String> mParams; 


public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener) 
{ 
    super(Method.POST, url, errorListener); 
    mListener = listener; 

    buildMultipartEntity(); 
} 

private void buildMultipartEntity() 
{ 
    entity.addPart("profile_picture", new FileBody(new File("/storage/emulated/0/Pictures/VSCOCam/2015-07-31 11.55.14 1.jpg"))); 
    try 
    { 
     entity.addPart("user_id", new StringBody("15")); 
     entity.addPart("name", new StringBody("Bogs")); 
     entity.addPart("gender", new StringBody("Male")); 
     entity.addPart("date_birth", new StringBody("1999-12-5")); 
     entity.addPart("breed", new StringBody("monkey")); 
    } 
    catch (UnsupportedEncodingException e) 
    { 
     VolleyLog.e("UnsupportedEncodingException"); 
    } 
} 

@Override 
public String getBodyContentType() 
{ 
    return entity.getContentType().getValue(); 
} 

@Override 
public byte[] getBody() throws AuthFailureError 
{ 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    try 
    { 
     entity.writeTo(bos); 
    } 
    catch (IOException e) 
    { 
     VolleyLog.e("IOException writing to ByteArrayOutputStream"); 
    } 
    return bos.toByteArray(); 
} 

@Override 
protected Response<String> parseNetworkResponse(NetworkResponse response) 
{ 
    return Response.success("Uploaded", getCacheEntry()); 
} 

@Override 
protected void deliverResponse(String response) 
{ 
    mListener.onResponse(response); 

} 

Quando aggiungo questa richiesta alla mia coda di richieste, risponde a com.android.volley.TimeoutError ma se si verifica il data base, la richiesta viene eseguita e aggiunta alla tabella ma il caricamento dell'immagine del profilo ha solo 1 byte di dimensione. un altro problema, il mio elemento del database è stato aggiunto due volte.

PROBLEMA RISOLTO Ho già risolto questo impostando il tempo di richiesta. ciò che è stato che è successo è che non sono in grado di ottenere la risposta dal mio server dopo il timeout predefinito di libreria di volley in modo da impostare il mio timeout chiamando e l'impostazione di questo metodo per la mia richiesta di coda:

multipartRequest.setRetryPolicy(new DefaultRetryPolicy(1000 * 60, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
       DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); 
+0

Partenza qui: - http://stackoverflow.com/a/19981901/4018207 – AndiGeeky

+0

Si può leggere [la mia domanda e risposta qui] (http://stackoverflow.com/questions/32240177/working-post-multipart-request-with-volley-and-without-httpentity). Spero che questo ti aiuti! – BNK

+0

@MamataGelanee come posso ottenere la classe MultipartEntity? im importazione di questo throug mia Gradle ** compilare gruppo: 'org.apache.httpcomponents', il nome: 'httpclient-Android' **, versione: '4.3.5.1' ma sembra che MultipartEntity è ancora mancante. –

risposta

7

Ho commentato ma forse non ho ancora letto Quindi ecco la mia risposta.

Se si desidera utilizzare Volley, è possibile fare riferimento ad alcune seguenti link:

  1. Working POST Multipart Request with Volley and without HttpEntity
  2. How to send a “multipart/form-data” POST in Android with Volley
  3. Trouble Sending Multipart File with Boundary via Volley

Spero che questo aiuti

+2

Non so perché, ma ottengo sempre una scrittura IOException per errore ByteArrayOutputStream mentre getBody è chiamato –

+0

Posta più codice e logcat completo – BNK

+0

Devo sovrascrivere il mio getParams() come ho fatto io il mio esempio o dovrei semplicemente aggiungere il mio parametro a MultipartEntityBuilder throught addTextBody() –

Problemi correlati