java httpclient文件上傳下載接口實現

	// download file ,兩個都要帶路徑
	public static void downloadfile(String url,String localfileName,String remotefileName) {
		FileOutputStream output = null;
		InputStream in = null;
		CloseableHttpClient httpclient=getignoreSSLClient();
		try {
		get=new HttpGet(url);
		get.addHeader("fileName",remotefileName );
		response=httpclient.execute(get);
		entity =response.getEntity();
		in = entity.getContent();
		long length = entity.getContentLength();
		if (length <= 0) {
			return;
		}
		File localfile = new File(localfileName);
		
		if(! localfile.exists()) {
			localfile.createNewFile();
		}
		output=new FileOutputStream(localfile);
	    byte[] buffer = new byte[4096];
	    int readLength = 0;
	    while ((readLength=in.read(buffer)) > 0) {
	    byte[] bytes = new byte[readLength];
	    System.arraycopy(buffer, 0, bytes, 0, readLength);
	    output.write(bytes);
	                 }         
	    output.flush();
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(in !=null) {
					in.close();
				}
				if(output !=null) {
					output.close();
				}
			}catch (IOException e) {
				e.printStackTrace();
			} 
		}		
	}
	
	// uploadfile 
	public static void uploadfile(String localfilepath,String url) {
		
		
		CloseableHttpClient httpclient=getignoreSSLClient();
		try {
		post = new HttpPost(url);
		FileBody bin=new FileBody(new File(localfilepath));
		HttpEntity reentity= MultipartEntityBuilder.create().addPart("bin",bin).build();
		post.setEntity(entity);
		response=httpclient.execute(post);
		entity=response.getEntity();
		if(entity!=null) {
			// length entity.getContentLength();
			String content=EntityUtils.toString(entity,"utf-8");
			EntityUtils.consume(entity);
		}
		
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(httpclient!=null ) {
					httpclient.close();
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
			
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章