利用HttpUrlConnection 上傳 接收檔案的實現方法_java

來源:互聯網
上載者:User

如下所示:

//用戶端代碼public static void main(String[] args) throws IOException { DataInputStream in = null; OutputStream out = null; HttpURLConnection conn = null; JSONObject resposeTxt = null; InputStream ins = null; ByteArrayOutputStream outStream = null; try {  URL url = new URL("http://10.28.160.160:9080/main/uploadFile?fileName=列表.txt");  conn = (HttpURLConnection) url.openConnection();  // 發送POST請求必須設定如下兩行  conn.setDoOutput(true);  conn.setUseCaches(false);  conn.setRequestMethod("POST");  conn.setRequestProperty("Content-Type", "text/html");  conn.setRequestProperty("Cache-Control", "no-cache");  conn.setRequestProperty("Charsert", "UTF-8");  conn.connect();  conn.setConnectTimeout(10000);  out = conn.getOutputStream();  File file = new File("H:/Users/chengtingyu/Desktop/test/list.txt");  in = new DataInputStream(new FileInputStream(file));  int bytes = 0;  byte[] buffer = new byte[1024];  while ((bytes = in.read(buffer)) != -1) {  out.write(buffer, 0, bytes);  }  out.flush();  // 返迴流  if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {  ins = conn.getInputStream();  outStream = new ByteArrayOutputStream();  byte[] data = new byte[1024];  int count = -1;  while ((count = ins.read(data, 0, 1024)) != -1) {   outStream.write(data, 0, count);  }  data = null;  resposeTxt = JSONObject.parseObject(new String(outStream   .toByteArray(), "UTF-8"));  } } catch (Exception e) {  e.printStackTrace(); } finally {  if (in != null) {  in.close();  }  if (out != null) {  out.close();  }  if (ins != null) {  ins.close();  }  if (outStream != null) {  outStream.close();  }  if (conn != null) {  conn.disconnect();  } } } //服務端代碼 public String uploadFile() throws Exception{    String fileName = request.getParameter("fileName");      String fileFullPath = "H:/Users/chengtingyu/Desktop/" + fileName;    InputStream input = null;    FileOutputStream fos = null; try {  input = request.getInputStream();  File file = new File("H:/Users/chengtingyu/Desktop");       if(!file.exists()){         file.mkdirs();       }       fos = new FileOutputStream(fileFullPath);       int size = 0;       byte[] buffer = new byte[1024];       while ((size = input.read(buffer,0,1024)) != -1) {         fos.write(buffer, 0, size);       }          //響應資訊 json字串格式     Map<String,Object> responseMap = new HashMap<String,Object>();     responseMap.put("flag", true);          //產生響應的json字串      String jsonResponse = JSONObject.toJSONString(responseMap);     sendResponse(jsonResponse); } catch (IOException e) {  //響應資訊 json字串格式     Map<String,Object> responseMap = new HashMap<String,Object>();     responseMap.put("flag", false);     responseMap.put("errorMsg", e.getMessage());     String jsonResponse = JSONObject.toJSONString(responseMap);     sendResponse(jsonResponse); } finally{  if(input != null){  input.close();  }  if(fos != null){  fos.close();  } }            return null; }    /**   * 返迴響應   *    * @throws Exception   */  private void sendResponse(String responseString) throws Exception {   response.setContentType("application/json;charset=UTF-8");    PrintWriter pw = null;    try {      pw = response.getWriter();      pw.write(responseString);      pw.flush();    } finally {      IOUtils.closeQuietly(pw);    }  }

以上這篇利用HttpUrlConnection 上傳 接收檔案的實現方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.