2011-10-10 39 views
5

tương đương trong java cho lệnh curl sau là gì:"Curl -F" Java tương đương

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

Yêu cầu tôi muốn thực hiện sử dụng Java là:

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

Tôi đã cố gắng:

  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

Chính xác thì vấn đề của bạn là gì? Và một mã mroe bit sẽ hữu ích, 'httpPost' là gì? –

+0

Tôi đang cố gắng để gửi lệnh curl (đã là một lệnh thiết bị đầu cuối Linux) bằng cách sử dụng một chương trình java. Tôi đã thử nhiều phần nhưng tôi không cần phải tải lên hoặc tải xuống tệp, nó là một sự chuyển giữa kho lưu trữ ở xa. – amine

+0

Vâng, mã Java của bạn chưa hoàn thành. Và chúng tôi không biết tại sao nó không hoạt động. Vì vậy, đăng thêm mã xin vui lòng (và có, tất cả chúng ta biết những gì 'curl' là .... thở dài). Ví dụ. bạn không gọi bất kỳ phương thức hậu pháp nào, do đó, phân đoạn ở trên không thể hoạt động, rõ ràng. Bạn cần ít nhất một HttpURLConnection ... –

Trả lời

1

Tôi đã gặp phải vấn đề này ngày hôm qua. Đây là một giải pháp sử dụng thư viện http 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())); 
    } 
} 

Đặt tệpPath và url nếu cần. Nếu bạn đang sử dụng một cái gì đó khác hơn là một tập tin, bạn có thể thay thế FileBody bằng ByteArrayBody, InputStreamBody hoặc StringBody. Tình huống cụ thể của tôi được gọi là ByteArrayBody nhưng đoạn mã trên hoạt động cho một tệp.