2011-10-10 103 views
5

什么是Java中的等值以下的curl命令:“卷曲-F” 相当于Java

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

请求我想用Java来执行的是:

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

我尝试:

  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

你的问题到底是什么?有一点mroe的代码会有帮助,例如'httpPost'是什么? –

+0

我正在尝试使用java程序发送curl命令(已经是Linux终端命令)。我尝试过多部分,但我不需要上传或下载文件,而是远程存储库之间的转移。 – amine

+0

那么,你的Java代码是不完整的。我们不知道为什么它不起作用。所以请张贴更多的代码(是的,我们都知道'curl'是......叹了口气)。例如。你不会调用任何post-method,所以上面的片段显然不能工作。您至少需要一个HttpURLConnection ... –

回答

1

昨天我遇到了这个问题。这是一个使用Apache http库的解决方案。

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())); 
    } 
} 

根据需要设置filePath和url。如果您使用的不是文件,您可以用FileBody替换ByteArrayBody,InputStreamBody或StringBody。我特别需要的是ByteArrayBody,但上面的代码适用于文件。