2016-02-05 69 views
2

我有一個捲曲的呼叫這樣上傳文件:如何使用Apache HttpPost

curl -i -X POST -H "Content-Type: multipart/form-data" -F "[email protected]_test/json_test.json" http://domain.com/api/upload_json/ 

所有我需要做的是一個Java實現這個呼叫。我已經創建了這個代碼,但是這個文件似乎是空的。

public static void uploadJson(String url, File jsonFile) { 
    try { 
     HttpPost request = new HttpPost(url); 
     EntityBuilder builder = EntityBuilder 
       .create() 
       .setFile(jsonFile) 
       .setContentType(ContentType 
         .MULTIPART_FORM_DATA) 
       .chunked(); 
     HttpEntity entity = builder.build(); 
     request.setEntity(entity); 
     HttpResponse response = getHttpClient().execute(request); 
     logger.info("Response: {}", response.toString()); 
    } catch (IOException e) { 
     logger.error(e.getMessage()); 
    } 
} 

什麼是構建此請求的正確方法?

回答

5
CloseableHttpClient httpClient = HttpClientBuilder.create() 
     .build(); 

HttpEntity requestEntity = MultipartEntityBuilder.create() 
     .addBinaryBody("file", new File("data_test/json_test.json")) 
     .build(); 
HttpPost post = new HttpPost("http://domain.com/api/upload_json/"); 
post.setEntity(requestEntity); 
try (CloseableHttpResponse response = httpClient.execute(post)) { 
    System.out.print(response.getStatusLine()); 
    EntityUtils.consume(response.getEntity()); 
} 
+0

它就像一個魅力,非常感謝你:) –