2016-10-04 41 views
-1

我的文件駐留在我的機器上的某個位置,如C://users//abc.txt,我想編寫一個Java程序來使用REST API通過HTTP傳輸此文件。我用MockHttpServelet請求創建的要求,但不知何故,我無法將文件使用Rest API通過HTTP將文件從Java後端上載到遠程服務器的問題。

+0

不知道關於REST API,但是我已經使用MySql作爲後端上載了服務器上的文件。 –

+0

不知道你使用的是什麼,是MongoDB嗎? –

+0

Milind,獨立Java應用程序正在後端運行。我有一個使用Rest API將文件從我的目錄傳輸到某個服務器的功能。服務器接受Rest API Resquest。我不想使用任何協議如scp來進行文件傳輸。服務器將只通過Rest API接受請求 –

回答

0

使用HttpClient轉移:

String url = "http://localhost:8080/upload"; // Replace with your target 'REST API' url 
String filePath = "C://users//abc.txt"; 

CloseableHttpClient httpClient = HttpClients.createDefault(); 
try { 
    HttpPost httpPost = new HttpPost(url); 
    FileEntity entity = new FileEntity(new File(filePath), ContentType.TEXT_PLAIN); 
    httpPost.setEntity(entity); 

    HttpResponse httpResponse = httpClient.execute(httpPost); 
    System.out.println(httpResponse.getStatusLine().getStatusCode()); // Check HTTP code 
} finally { 
    httpClient.close(); 
} 

身份驗證:

String url = "http://localhost:8080/upload"; // Replace with your target 'REST API' url 
String filePath = "C://users//abc.txt"; 
String username = "username"; // Replace with your username 
String password = "password"; // Replace with your password 

RequestConfig requestConfig = 
    RequestConfig.custom(). 
    setAuthenticationEnable(true). 
    build(); 

CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); 
credentialsProvider.setCredentials(
    AuthScope.ANY, 
    new UsernamePasswordCredential(username, password)); 

CloseableHttpClient httpClient = 
    HttpClients.custom(). 
    setDefaultRequestConfig(requestConfig). 
    setDefaultCredentialsProvider(credentialsProvider). 
    build(); 
try { 
    HttpPost httpPost = new HttpPost(url); 
    FileEntity entity = new FileEntity(new File(filePath), ContentType.TEXT_PLAIN); 
    httpPost.setEntity(entity); 

    HttpResponse httpResponse = httpClient.execute(httpPost); 
    System.out.println(httpResponse.getStatusLine().getStatusCode()); // Check HTTP code 
} finally { 
    httpClient.close(); 
} 
+0

感謝Greg。任何想法需要指定session/userCredentials,以便服務器可以訪問它? –

+0

身份驗證使用是另一個問題。 使用HttpClients.custom()。setDefaultRequestConfig(requestConfig).setDefaultCredentialsProvider(credentialsProvider)。 –

+0

它會不會影響性能?我的意思是當文件打開傳輸時,JVM會將文件加載到內存中。如果它很大,我相信會有性能問題。任何想法如何可以避免? –

0
String location="C:\\Usersabc.img"; 
Path path = Paths.get(location); 
String name=location.substring(location.lastIndexOf("\\")+1); 
MultipartEntity multipart= new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);     
    try { 
    multipart.addPart("image", new ByteArrayBody(Files.readAllBytes(path), ContentType.APPLICATION_OCTET_STREAM.getMimeType(),name));     
     } 
     catch (IOException ex) { 
        // TODO Auto-generated catch block 
        ex.printStackTrace(); 
       } 
+0

這也適用於我 –

相關問題