2011-08-02 134 views
11

Estoy desarrollando un cliente J2ME que debe cargar un archivo a un servlet usando HTTP.Java Http Client para cargar el archivo a través de POST

La parte servlet está cubierta usando Apache Commons FileUpload

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
{  

    ServletFileUpload upload = new ServletFileUpload(); 
    upload.setSizeMax(1000000); 

    File fileItems = upload.parseRequest(request); 

    // Process the uploaded items 
    Iterator iter = fileItems.iterator(); 
    while (iter.hasNext()) { 
     FileItem item = (FileItem) iter.next(); 
     File file = new File("\files\\"+item.getName()); 
     item.write(file); 
    } 
} 

Commons Subir parece ser capaz de cargar único archivo de varias partes, pero ninguna aplicación/octect-stream.

Pero para el lado del cliente no hay clases Multipart, tampoco, en este caso, es posible utilizar cualquier biblioteca HttpClient.

Otra opción podría ser utilizar la carga HTTP Chunk, pero no he encontrado un ejemplo claro de cómo esto podría implementarse, especialmente en el lado del servlet.

Mis opciones son: - Implementar un servlet para la carga http trozo - Implementar un cliente http prima para la creación de varias partes

No sé cómo poner en práctica ninguna de las opciones anteriores. ¿Alguna sugerencia?

Respuesta

0

Sin entrar en detalles sangrientos su código se ve bien.

Ahora necesita el lado del servidor. Te recomendaría que uses Yakarta FileUpload, para que no tengas que implementar nada. Solo despliega y configura.

+5

¿Leyó usted la pregunta? El código publicado ** es ** el lado del servidor que ya utiliza FileUpload. – BalusC

29

Se supone que el envío de archivos a través de HTTP se realiza utilizando la codificación multipart/form-data. Su parte de servlet está bien ya que usa Apache Commons FileUpload para analizar una solicitud multipart/form-data.

Sin embargo, su parte de cliente aparentemente no está bien ya que aparentemente está escribiendo el contenido del archivo sin procesar en el cuerpo de la solicitud. Debe asegurarse de que su cliente envíe una solicitud correcta de multipart/form-data. La forma exacta de hacerlo depende de la API que está utilizando para enviar la solicitud HTTP. Si es simple vainilla java.net.URLConnection, entonces puede encontrar un ejemplo concreto en algún lugar cerca de la parte inferior de this answer. Si está utilizando Apache HttpComponents Client para esto, entonces esto es un ejemplo concreto:

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost(url); 

MultipartEntity entity = new MultipartEntity(); 
entity.addPart("file", new FileBody(file)); 
post.setEntity(entity); 

HttpResponse response = client.execute(post); 
// ... 

Sin relación al problema concreto, hay un error en el código del lado del servidor:

File file = new File("\files\\"+item.getName()); 
item.write(file); 

Este potencialmente sobrescribirá cualquier archivo previamente subido con el mismo nombre. Sugeriría utilizar File#createTempFile() para esto en su lugar.

String name = FilenameUtils.getBaseName(item.getName()); 
String ext = FilenameUtils.getExtension(item.getName()); 
File file = File.createTempFile(name + "_", "." + ext, new File("/files")); 
item.write(file); 
+0

cómo puedo obtener este lado del servidor de archivos, por ejemplo, usando requset.getParameter obtenemos valores de cadena, ¿qué pasa con el archivo del cuerpo del archivo ... – Aniket

+0

@Aniket: exactamente de la misma manera que cuando usas un formulario HTML normal. – BalusC

+4

[MultipartEntity] (http://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/MultipartEntity.html) ahora está en desuso. –

0

Gracias por todo el código Ive disparado ... Aquí hay algunos de nuevo.

Gradle 

compile "org.apache.httpcomponents:httpclient:4.4" 
compile "org.apache.httpcomponents:httpmime:4.4" 



import java.io.File; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.StringWriter; 
import java.util.Map; 

import org.apache.commons.io.IOUtils; 
import org.apache.http.HttpEntity; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.CloseableHttpResponse; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.ContentType; 
import org.apache.http.entity.mime.MultipartEntityBuilder; 
import org.apache.http.entity.mime.content.FileBody; 
import org.apache.http.entity.mime.content.StringBody; 
import org.apache.http.impl.client.CloseableHttpClient; 
import org.apache.http.impl.client.HttpClients; 


public class HttpClientUtils { 

    public static String post(String postUrl, Map<String, String> params, 
      Map<String, String> files) throws ClientProtocolException, 
      IOException { 
     CloseableHttpResponse response = null; 
     InputStream is = null; 
     String results = null; 
     CloseableHttpClient httpclient = HttpClients.createDefault(); 

     try { 

      HttpPost httppost = new HttpPost(postUrl); 

      MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 

      if (params != null) { 
       for (String key : params.keySet()) { 
        StringBody value = new StringBody(params.get(key), 
          ContentType.TEXT_PLAIN); 
        builder.addPart(key, value); 
       } 
      } 

      if (files != null && files.size() > 0) { 
       for (String key : files.keySet()) { 
        String value = files.get(key); 
        FileBody body = new FileBody(new File(value)); 
        builder.addPart(key, body); 
       } 
      } 

      HttpEntity reqEntity = builder.build(); 
      httppost.setEntity(reqEntity); 

      response = httpclient.execute(httppost); 
      // assertEquals(200, response.getStatusLine().getStatusCode()); 

      HttpEntity entity = response.getEntity(); 
      if (entity != null) { 
       is = entity.getContent(); 
       StringWriter writer = new StringWriter(); 
       IOUtils.copy(is, writer, "UTF-8"); 
       results = writer.toString(); 
      } 

     } finally { 
      try { 
       if (is != null) { 
        is.close(); 
       } 
      } catch (Throwable t) { 
       // No-op 
      } 

      try { 
       if (response != null) { 
        response.close(); 
       } 
      } catch (Throwable t) { 
       // No-op 
      } 

      httpclient.close(); 
     } 

     return results; 
    } 

    public static String get(String getStr) throws IOException, 
      ClientProtocolException { 
     CloseableHttpResponse response = null; 
     InputStream is = null; 
     String results = null; 
     CloseableHttpClient httpclient = HttpClients.createDefault(); 

     try { 
      HttpGet httpGet = new HttpGet(getStr); 
      response = httpclient.execute(httpGet); 

      assertEquals(200, response.getStatusLine().getStatusCode()); 

      HttpEntity entity = response.getEntity(); 
      if (entity != null) { 
       is = entity.getContent(); 
       StringWriter writer = new StringWriter(); 
       IOUtils.copy(is, writer, "UTF-8"); 
       results = writer.toString(); 
      } 

     } finally { 

      try { 
       if (is != null) { 
        is.close(); 
       } 
      } catch (Throwable t) { 
       // No-op 
      } 

      try { 
       if (response != null) { 
        response.close(); 
       } 
      } catch (Throwable t) { 
       // No-op 
      } 

      httpclient.close(); 
     } 

     return results; 
    } 

} 
0

el código siguiente se puede utilizar para cargar el archivo con 4.x de cliente HTTP (Por encima de respuesta utiliza MultipartEntity, se prescinde de ahora)

String uploadFile(String url, File file) throws IOException 
{ 
    HttpPost post = new HttpPost(url); 
    post.setHeader("Accept", "application/json"); 
    _addAuthHeader(post); 
    MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 
    // fileParamName should be replaced with parameter name your REST API expect. 
    builder.addPart("fileParamName", new FileBody(file)); 
    //builder.addPart("optionalParam", new StringBody("true", ContentType.create("text/plain", Consts.ASCII))); 
    post.setEntity(builder.build()); 
    HttpResponse response = getClient().execute(post);; 
    int httpStatus = response.getStatusLine().getStatusCode(); 
    String responseMsg = EntityUtils.toString(response.getEntity(), "UTF-8"); 

    // If the returned HTTP response code is not in 200 series then 
    // throw the error 
    if (httpStatus < 200 || httpStatus > 300) { 
     throw new IOException("HTTP " + httpStatus + " - Error during upload of file: " + responseMsg); 
    } 

    return responseMsg; 
} 
Cuestiones relacionadas