2011-10-10 21 views
5

¿Cuál es el equivalente en java para el siguiente comando curl:"Curl -F" equivalente Java

curl -X POST -F "[email protected]$File_PATH" 

La petición que desee ejecutar utilizando Java es:

curl -X POST -F '[email protected]_path' http://localhost/files/ 

yo estaba tratando:

  HttpClient httpClient = new DefaultHttpClient();   

    HttpPost httpPost = new HttpPost(_URL); 

    File file = new File(PATH); 

      MultipartEntity mpEntity = new MultipartEntity(); 
     ContentBody cbFile = new FileBody(file, "bin"); 
     mpEntity.addPart("userfile", cbFile); 

     httpPost.setEntity(mpEntity); 

    HttpResponse response = httpClient.execute(httpPost); 
    InputStream instream = response.getEntity().getContent(); 
+0

¿Cuál es exactamente tu problema? Y un poco de código mroe sería útil, ¿qué es 'httpPost', por ejemplo? –

+0

Estoy tratando de enviar el comando curl (ya es un comando del terminal Linux) usando un programa java. Lo he intentado en varias partes pero no necesito cargar o descargar el archivo, es más bien una transferencia entre repositorio distante. – amine

+0

Bueno, su código de Java está incompleto. Y no sabemos por qué no funciona. Así que publica más código por favor (y sí, todos sabemos qué es 'curl' ... suspiro). P.ej. no llama a ningún método posterior, por lo que ese fragmento anterior no puede funcionar, obviamente. Necesita al menos un HttpURLConnection ... –

Respuesta

1

Ayer encontré este problema. Aquí hay una solución que usa las bibliotecas http de Apache.

package curldashf; 

import java.io.File; 
import java.io.IOException; 
import org.apache.commons.io.FileUtils; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.fluent.Request; 
import org.apache.http.entity.mime.MultipartEntity; 
import org.apache.http.entity.mime.content.ByteArrayBody; 
import org.apache.http.util.EntityUtils; 

public class CurlDashF 
{ 
    public static void main(String[] args) throws ClientProtocolException, IOException 
    { 
     String filePath = "file_path"; 
     String url = "http://localhost/files"; 
     File file = new File(filePath); 
     MultipartEntity entity = new MultipartEntity(); 
     entity.addPart("file", new FileBody(file)); 
     HttpResponse returnResponse = Request.Post(url) 
      .body(entity) 
      .execute().returnResponse(); 
     System.out.println("Response status: " + returnResponse.getStatusLine().getStatusCode()); 
     System.out.println(EntityUtils.toString(returnResponse.getEntity())); 
    } 
} 

Establezca filePath y url según sea necesario. Si está utilizando algo que no sea un archivo, puede sustituir FileBody con ByteArrayBody, InputStreamBody o StringBody. Mi situación particular requería ByteArrayBody pero el código anterior funciona para un archivo.