2017-05-04 45 views
1

我有點迷路了這個問題,需要一些幫助。我需要做的是使用Java向HTTP REST接口發出發佈請求。在這個請求中,我需要發送密鑰作爲參數,並且需要將文本文件上傳到服務器。該文件將在本地可用。POST txt文件到遠程HTTP服務器

這裏沒有用戶輸入。我不知道如何上傳文件到該服務器在此寫入

這一步的指示頁面需要一個HTTP POST請求URI「someurl.com」

  • 隨着HTTP郵政變量命名的鍵,它的價值
  • 和in.txt文件附

提出這個要求,我會得到一個out.txt文件作爲響應後。

到目前爲止,在互聯網上我發現這個代碼,這是接近

dos.writeBytes(message); //here message is String and dos is DataOutputStream 
     dos.flush(); 
     dos.close(); 

但這裏的消息是字符串,我想知道是否有一種方法來發送文件到服務器。

+0

代碼你需要這樣的:http://hc.apache.org/httpclient-3.x/methods/multipartpost.html – wannadream

回答

-1

是在按摩參數中,您需要序列化您的文件 - 將其轉換爲字節,然後對其進行加密。然後將其作爲消息發送。然後解密並建立在對對方

+0

服務器的URL,我將文件發送到是不是我的。這是我用來執行我需要的計算的一些遠程服務器。 – denis

0

你可以用這個方法來上傳文件,一些關鍵和值參數

CloseableHttpClient httpClient = HttpClients.createDefault(); 
    HttpPost uploadFile = new HttpPost("someurl.com"); 
    //Post variable named key and its value 
    MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 
    builder.addTextBody("id", id, ContentType.TEXT_PLAIN); 
    builder.addTextBody("apd", apd, ContentType.TEXT_PLAIN); 

    //path of file 
    String filepath = "C:\Users\Downloads\images\file.txt";  
    // This attaches the file to the POST: 
    File f = new File(filepath); 
    builder.addBinaryBody(
     "file", 
     new FileInputStream(f), 
     ContentType.APPLICATION_OCTET_STREAM, 
     f.getName() 
    ); 

    HttpEntity multipart = builder.build(); 
    uploadFile.setEntity(multipart); 
    CloseableHttpResponse response = httpClient.execute(uploadFile); 
    HttpEntity responseEntity = response.getEntity(); 
0

傢伙感謝您的答案,但他們沒有工作從字節文件爲了我。我對這種API沒有太多經驗。在幫助部分,我發現使用捲曲並能夠成功獲得結果。下面是我用

String[] command = {"curl","-H","key:keyValue","-F","[email protected]", 
        "http://example.com/evaluate.php ","-o","output.txt"}; 
ProcessBuilder process = new ProcessBuilder(command); 
Process p; 
p = process.start();