使用HttpClient實現客戶端(非瀏覽器)檔案的上傳下載
阿新 • • 發佈:2018-12-12
public static void main(String[] args) { String remoteFileName=""; String localFileName="E:\\test.zip"; HttpClient client = new HttpClient(); PostMethod get = null; FileOutputStream output = null; try { String url="http://10.39.136.175:18081/acs-app-api/appi/busi/remote/getIcCardsFileByDevid?sign=2d0e3c349dbf29470c1b89dfd895e2ae×tamp=1538305948"; get = new PostMethod(url); get.setRequestHeader("Content-Type","application/json"); // get.setRequestHeader("fileName", remoteFileName); /*get.addParameter("devIds", "SR-0699010000023"); get.addParameter("projectCode", "857196");*/ String str="{\"devIds\":\"SR-0699010000023\",\"projectCode\":\"857196\"}"; get.setRequestBody(str); System.out.println("==============="+str); int i = client.executeMethod(get); System.out.println("==============="+i); // if (SUCCESS == i) { if (200 == i) { System.out.println("The response value of token:" + get.getResponseHeader("token")); File storeFile = new File(localFileName); if(!storeFile.exists()){ storeFile.createNewFile(); } output = new FileOutputStream(storeFile); IOUtils.copy(get.getResponseBodyAsStream(),output); // 得到網路資源的位元組陣列,並寫入檔案 // output.write(get.getResponseBody()); } else { System.out.println("DownLoad file occurs exception, the error code is :" + i); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (output != null) { output.close(); } } catch (IOException e) { e.printStackTrace(); } get.releaseConnection(); client.getHttpConnectionManager().closeIdleConnections(0); }