Subir fotos usando HttpPost MultiPartEntityBuilder
Estoy intentando cargar la foto tomada al servidor. esto es lo que hago:
public JSONObject makePostFileRequest(String url, String photoFile) { try { // photoFile = /path/tofile/pic.jpg DefaultHttpClient httpClient = GlobalData.httpClient; HttpPost httpPost = new HttpPost(url); File file = new File(photoFile); FileBody fileBody = new FileBody(file); // here is line 221 MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("PhotoMessage", fileBody); httpPost.setEntity(multipartEntity.build()); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent();
Consigo este error:
- Google TTS API para árabe, chino y griego
- Cómo solucionar el error "Uso no válido de BasicClientConnManager: Asegúrese de liberar la conexión antes de asignar otra" en Android?
- Proteger la solicitud HTTP de ser llamada por otros
- Servidor ByetHost que pasa valores html "Comprobación de su navegador" con JSON String
- Establecer el tiempo de espera en el cliente asíncrono HTTP
11-29 13: 12: 14.924: E / AndroidRuntime (15781): Causado por: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType 11-29 13: 12: 14.924: E / AndroidRuntime (15781): En org.apache.http.entity.mime.content.FileBody. (FileBody.java:89) 11-29 13: 12: 14.924: E / AndroidRuntime (15781): en com.petcial.petopen.custom.JSONParser.makePostFileRequest (JSONParser.java:221)
¿Qué estoy haciendo mal?
Actualizar
InputStream inputStream; inputStream = new FileInputStream(new File(photoFile)); byte[] data; data = IOUtils.toByteArray(inputStream); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent")); InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), "Pic.jpg"); MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create(); multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("PhotoMessage", inputStreamBody); httpPost.setEntity(multipartEntity.build()); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent();
Aquí está el error:
11-29 14: 00: 33.364: E / AndroidRuntime (19478): Causado por: java.lang.NoClassDefFoundError: org.apache.http.util.Args 11-29 14: 00: 33.364: E / AndroidRuntime (19478): En org.apache.http.entity.mime.content.AbstractContentBody. (AbstractContentBody.java:48) 11-29 14: 00: 33.364: E / AndroidRuntime (19478): en org.apache.http.entity.mime.content .InputStreamBody. (InputStreamBody.java:69) 11-29 14: 00: 33.364: E / AndroidRuntime (19478): en org.apache.http.entity.mime.content.InputStreamBody. (InputStreamBody.java:62) 11- 29 14: 00: 33.364: E / AndroidRuntime (19478): en com.petcial.petopen.custom.JSONParser.makePostFileRequest (JSONParser.java:233)
Estas bibliotecas resolvieron mi problema:
- VolleyPlus: NetworkDispatcher.run: Excepción no controlada java.lang.NullPointerException
- Error de autenticación: no se puede responder a ninguno de estos desafíos: {} Android - 401 no autorizado
- Rutas dinámicas en la adaptación
- Cómo inspeccionar las solicitudes HTTP hechas por WebViews
- Android: howto parse URL String con espacios al objeto URI?
- Solicitud personalizada Angular2
- ProtocolException: encabezado no válido:: en HTTPRequest
- Android ignora el parámetro de tiempo de espera DefaultHttpClient
Compruebe ese tarro en la pestaña de orden y exportación y ejecute.
Hay mi solución de trabajo para enviar la imagen con el poste, usando las bibliotecas de http del apache (muy importante aquí es el límite agrega No trabajará sin él en mi conexión):
ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] imageBytes = baos.toByteArray(); HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(StaticData.AMBAJE_SERVER_URL + StaticData.AMBAJE_ADD_AMBAJ_TO_GROUP); String boundary = "-------------" + System.currentTimeMillis(); httpPost.setHeader("Content-type", "multipart/form-data; boundary="+boundary); ByteArrayBody bab = new ByteArrayBody(imageBytes, "pic.png"); StringBody sbOwner = new StringBody(StaticData.loggedUserId, ContentType.TEXT_PLAIN); StringBody sbGroup = new StringBody("group", ContentType.TEXT_PLAIN); HttpEntity entity = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .setBoundary(boundary) .addPart("group", sbGroup) .addPart("owner", sbOwner) .addPart("image", bab) .build(); httpPost.setEntity(entity); try { HttpResponse response = httpclient.execute(httpPost); ...then reading response
Mejor pasar la ruta del archivo de imagen. A continuación se muestra mi código que he utilizado para cargar la imagen en el servidor.
public class UploadProductDetails { public void uploadProductDetails(String filePath, String fileName) { InputStream inputStream; try { inputStream = new FileInputStream(new File(filePath)); byte[] data; try { data = IOUtils.toByteArray(inputStream); HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent")); HttpPost httpPost = new HttpPost("http://ipaddress"); InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), "abc.png"); MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("file", inputStreamBody); httpPost.setEntity(multipartEntity); HttpResponse httpResponse = httpClient.execute(httpPost); // Handle response back from script. if(httpResponse != null) { //Toast.makeText(getBaseContext(), "Upload Completed. ", 2000).show(); } else { // Error, no response. //Toast.makeText(getBaseContext(), "Server Error. ", 2000).show(); } } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } } }
Tenga en cuenta que el uso de este código: new InputStreamBody(new ByteArrayInputStream(yourByteArray))
puede resultar en algunos problemas, ya que devuelve -1
al llamar a getContentLength()
.
En su lugar, utilice esto: new ByteArrayBody(yourByteArray)
- Se ha rechazado una tasa increíblemente alta de "tarjeta del cliente" en la API de suscripción
- Android: ¿Es una buena idea almacenar Token de autenticación en las preferencias compartidas?