• spring boot MVC作为服务器端, apache.httpclient作为客户端的文件传输模式(demo代码)


    最近做http协议下面的数据传输,总结一下
     
    1. 上传单个文件:
    服务器端代码:
     
        @RequestMapping(value = "/POST", method = RequestMethod.POST)
        @ResponseBody
        public String PostTest(String test_data, MultipartFile file ){
           System. out.println("comming here!" );
            if (!file .isEmpty()) { 
                try 
                    byte[] bytes file .getBytes();
                    BufferedOutputStream stream =  new BufferedOutputStream(
                                new FileOutputStream(new File("d:\temp\" test_data "-uploaded")));
                    stream.write( bytes);
                    stream.close();
                    return "You successfully uploaded " test_data " into " test_data "-uploaded !" ;
                } catch (Exception ) {
                    return "You failed to upload " test_data " => " e.getMessage();
                }
            } else {
                return "You failed to upload " test_data " because the file was empty.";
            }
        }
    客户端代码:
        public static void testUploadOne() throws ClientProtocolException, IOException{
                   @SuppressWarnings("resource" )
                  HttpClient httpclient new DefaultHttpClient() ;
                  HttpPost httppost new HttpPost("http://127.0.0.1:8080/POST/" );
                  FileBody fileContent new FileBody(new File( "D:\projectSet.psf"));
                  StringBody stringBody new StringBody ("123456" ); 
                   @SuppressWarnings("deprecation" )
                   MultipartEntity reqEntity new MultipartEntity();
     
                   reqEntity.addPart("file"fileContent);
                   reqEntity.addPart("test_data"stringBody );
                   httppost.setEntity( reqEntity);
                   try {
                         HttpResponse response httpclient.execute(httppost );
                          int statusCode response .getStatusLine().getStatusCode();
                          if(statusCode == HttpStatus.SC_OK){                
                               System. out.println("服务器正常响应....." );                       
                         HttpEntity resEntity response .getEntity();
                         
                          System.out.println(EntityUtils.toString(resEntity ));// httpclient自带的工具类读取返回数据 
                         System. out.println(resEntity .getContent());
                         
                         EntityUtils. consume(resEntity);
                         }
                  } catch (ClientProtocolException ) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                  } catch (IOException ) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                  }
        }
     
    2.
    一次上传多个文件:
    服务器端代码:
        public static String writeMulti(String test_data , MultipartFile file){
            if (!file .isEmpty()) { 
                try 
                    byte[] bytes file .getBytes ();
                    BufferedOutputStream stream =  new BufferedOutputStream(
                                new FileOutputStream( new File("d:\temp\" test_data)));
                    stream. write(bytes);
                    stream. close();
                    return "You successfully uploaded " test_data " into " test_data "!" ;
                } catch (Exception e) {
                    return "You failed to upload " test_data " => " e.getMessage();
                }
            } else {
                return "You failed to upload " test_data " because the file was empty.";
            }
        }
        @RequestMapping(value = "/TPOST", method = RequestMethod.POST)
        @ResponseBody
        public void Test(@RequestParam ("file_name" ) String[] file_name@RequestParam("file" ) MultipartFile[] file,
                  HttpServletRequest requestthrows FileUploadException, IOException{
            System. out.println("comming here!" );
            System. out.println("file name length: " file_name .length " file length: " file.length);
           writeMulti(file_name [0], file [0]);
           writeMulti(file_name [1], file [1]);
        }
    客户端代码:
            public static void testUploadMultiFiles() throws ClientProtocolException, IOException{
                   @SuppressWarnings("resource" )
                  HttpClient httpclient new DefaultHttpClient();
                  HttpPost httppost new HttpPost("http://127.0.0.1:8080/TPOST/" );
                  FileBody fileContent new FileBody(new File("C:\Users\Tangyun\Desktop\xiazai\lbfs.pdf" ));
                  FileBody fileContent1 new FileBody(new File("C:\Users\Tangyun\Desktop\xiazai\server_demo.erl" ));
                  StringBody stringBody new StringBody ("lbfs.pdf" );
                  StringBody stringBody1 new StringBody ("server_demo.erl" );
                   MultipartEntity reqEntity new MultipartEntity();
                  
                   // 你只传了一个参数 test_data  没有file , 而且test_data给的值是 文件
     
                   reqEntity.addPart("file" fileContent );
                   reqEntity.addPart("file_name" stringBody );
                   reqEntity.addPart("file" fileContent1 );
                   reqEntity.addPart("file_name" stringBody1 );
                   httppost.setEntity( reqEntity);
                   try {
                         HttpResponse response httpclient.execute(httppost );
                          int statusCode response .getStatusLine().getStatusCode();
                          if(statusCode == HttpStatus.SC_OK){                
                               System. out.println("服务器正常响应....." );                       
                         HttpEntity resEntity response .getEntity();
                         
                          System.out.println(EntityUtils.toString(resEntity ));// httpclient自带的工具类读取返回数据 
                         System. out.println(resEntity .getContent());
                         
                         EntityUtils. consume(resEntity);
                         }
                  } catch (ClientProtocolException ) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                  } catch (IOException ) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                  }
        }
     
    3.
    下载文件:
    服务器端代码:
        @RequestMapping(value = "/download", method = RequestMethod.GET)
        public static ResponseEntity<byte[]> downloadFile(String fileId) {
            HttpHeaders headers new HttpHeaders(); 
            headers.setContentType(MediaType. APPLICATION_OCTET_STREAM); 
            headers.setContentDispositionFormData( "attachment""dict.txt" );
            String downloadDataString "download success!" ;
            return new ResponseEntity<byte[]>( downloadDataString.getBytes(), 
                                              headers, HttpStatus. CREATED); 
        }
    客户端代码:
        public static void download() {
           HttpClient client new DefaultHttpClient();
            HttpGet httpGet new HttpGet("http://127.0.0.1:8080/download/" ); 
             try 
                   HttpResponse response  = client.execute( httpGet); 
                   HttpEntity entity response.getEntity(); 
                 InputStream in entity.getContent(); 
                 
                 FileOutputStream out new FileOutputStream(new File("D:\temp\download.txt" )); 
                 
                 byte[] new byte[1000]; 
                 int len = 0; 
                 while((len =in .read())!= -1){ 
                     out.write( b,0, len); 
                 } 
                 in.close(); 
                 out.close(); 
                  
             } catch (IOException ) { 
                 e.printStackTrace(); 
             } finally
                 httpGet.releaseConnection(); 
             } 
             System. out.println("download, success!!" );
        }
  • 相关阅读:
    [LeetCode] Same Tree, Solution
    图搜索
    1 sec on Large Judge (java): https://github.com/l...
    [LeetCode] Path Sum, Solution
    嗯哪
    海量数据处理总结
    [LeetCode] Unique Binary Search Trees II, Solution
    [Interview] Serialize and Deserialize a tree
    设计题
    [LeetCode] Convert Sorted Array to Binary Search Tree, Solution
  • 原文地址:https://www.cnblogs.com/candycloud/p/4449853.html
Copyright © 2020-2023  润新知