首页 > 编程知识 正文

Http工具类,访问外网需要使用代理

时间:2023-05-05 02:16:34 阅读:207634 作者:1079

import org/** * Http工具类 * */public class HttpFileUtil {private static final Logger log = LoggerFactory.getLogger(HttpFileUtil.class); /** 下载文件 * @param urlAddress 文件的网络地址 * @param downloadDir 保存的文件地址 */ public static String dowanloadFile(String urlAddress, String downloadDir ,String fileName,String fileKey) throws IOException { log.info("下载中..."); File filetemp = new File(downloadDir);if (!filetemp.exists()) {filetemp.mkdirs();};// 文件已经存在,拿到加密后文件路径,返回File localFile = new File(downloadDir + fileName);if (localFile.exists() ) {if (localFile.length()>0){ return "success"; }; }; InputStream inputStream = null; RandomAccessFile randomAccessFile = null; // 定义文件下载的目录与名称 String path = downloadDir + fileName; // 实例化文件对象 File file = new File(path); try { HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlAddress).openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(10 * 1000); // 判断文件路径是否存在 if (!file.getParentFile().exists()) { // 如果文件不存在就创建文件 file.getParentFile().mkdirs(); } int responseCode = urlConnection.getResponseCode(); if (responseCode >= 200 && responseCode < 300) { inputStream = urlConnection.getInputStream(); int len = 0; byte[] data = new byte[4096]; int progres = 0; //用于保存当前进度(具体进度) int maxProgres = urlConnection.getContentLength();//获取文件 try { randomAccessFile = new RandomAccessFile(file, "rwd"); randomAccessFile.setLength(maxProgres);//设置文件大小 int unit = maxProgres / 100;//将文件大小分成100分,每一分的大小为unit int unitProgress = 0; //用于保存当前进度(1~100%) while (-1 != (len = inputStream.read(data))) { randomAccessFile.write(data, 0, len); progres += len;//保存当前具体进度 int temp = progres / unit; //计算当前百分比进度 if (temp >= 1 && temp > unitProgress) {//如果下载过程出现百分比变化 unitProgress = temp;//保存当前百分比/* log.info("正在下载中..." + unitProgress + "%"); */ } } inputStream.close(); log.info("下载完成..."); } catch (Exception e) { log.info("服务器异常..."); return "fail"; } finally { if (null != randomAccessFile) { randomAccessFile.close(); } } } else { log.info("服务器异常..."); return "fail"; } } catch (Exception e) { log.info(e.getMessage());} finally { if (null != inputStream) { inputStream.close(); } } if(HCPClientUtils.doesObjectExist(fileKey+File.separator+fileName)) { return HCPClientUtils.getPresignedUrl(fileKey+File.separator+fileName); }else { return HCPClientUtils.putFile(fileKey+File.separator+fileName, file,1000*60*60*24*7 ); } } /** 下载文件 * @param urlAddress 文件的网络地址 * @param downloadDir 保存的文件地址 */ public static File dowanload(String urlAddress, String downloadDir ,String fileName) throws IOException { log.info("下载中..."); InputStream inputStream = null; RandomAccessFile randomAccessFile = null; // 定义文件下载的目录与名称 String path = downloadDir + fileName; // 实例化文件对象 File file = new File(path); try {// 访问外网需要使用代理//Proxy proxy = new Proxy(Proxy.Type.HTTP, new//InetSocketAddress("10.0.128.40", 8080)); //代理网IP和端口//// 添加验证信息的请求头 格式如下: "Proxy-Authorization"= "Basic//String headerKey = "Proxy-Authorization";//// 组装验证信息//String auth = "qtmp002:Mis09876";//String headerValue = "Basic " + Base64.encodeBase64(auth.getBytes());//HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlAddress).openConnection(proxy); HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlAddress).openConnection();urlConnection.setRequestProperty(headerKey, headerValue);//Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("10.0.60.78"/*proxy addr*/,8080/*proxy port*/));// HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlAddress).openConnection(proxy); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(10 * 1000); // 判断文件路径是否存在 if (!file.getParentFile().exists()) { // 如果文件不存在就创建文件 file.getParentFile().mkdirs(); } int responseCode = urlConnection.getResponseCode(); if (responseCode >= 200 && responseCode < 300) { inputStream = urlConnection.getInputStream(); int len = 0; byte[] data = new byte[4096]; int progres = 0; //用于保存当前进度(具体进度) int maxProgres = urlConnection.getContentLength();//获取文件 try { randomAccessFile = new RandomAccessFile(file, "rwd"); randomAccessFile.setLength(maxProgres);//设置文件大小 int unit = maxProgres / 100;//将文件大小分成100分,每一分的大小为unit int unitProgress = 0; //用于保存当前进度(1~100%) while (-1 != (len = inputStream.read(data))) { randomAccessFile.write(data, 0, len); progres += len;//保存当前具体进度 int temp = progres / unit; //计算当前百分比进度 if (temp >= 1 && temp > unitProgress) {//如果下载过程出现百分比变化 unitProgress = temp;//保存当前百分比// log.info("正在下载中..." + unitProgress + "%"); } } inputStream.close(); log.info("下载完成..."); } catch (Exception e) { log.info("服务器异常..."); return null; } finally { if (null != randomAccessFile) { randomAccessFile.close(); } } } else { log.info("服务器异常..."); return null; } } catch (Exception e) {// TODO Auto-generated catch block log.info(e.getMessage());} finally { if (null != inputStream) { inputStream.close(); } } return file; } /** * 微信下载文件 * * @param urlAddress 文件url地址 * @param downloadDir 文件保存的目录 * @return 文件 */ public static File WXdownloadFile(String downloadDir ,String fileName ,String serverId) { // 调用接口从微信服务器下载对应的图片String downloadWxFileURL = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";// 调用客服中心微信公众号后台webservice服务,获取ACCESS_TOKENString access_token = "";// 获取access_token的webservice接口地址String tokenwsurl = SysProperties.CSCHAT_TOKENWS;// 调用webserviceURL url = null;try {url = new URL(tokenwsurl);} catch (MalformedURLException e) {log.info(e.getMessage());}WexinAccessTokenWebserviceService weixinAccessTokenService = new WexinAccessTokenWebserviceService(url, new QName("http://ws.wxpp.gclife.com/","WexinAccessTokenWebserviceService"));WexinAccessTokenWebservice wactService = weixinAccessTokenService.getWexinAccessTokenWebservicePort();Map<String, Object> requestContext = ((BindingProvider) wactService).getRequestContext();// 设置调用webservice超时时间requestContext.put("com.sun.xml.internal.ws.connect.timeout",1000 * 120);// Timeout in millisrequestContext.put("com.sun.xml.internal.ws.request.timeout",1000 * 120);// Timeout in millistry {access_token = wactService.getWeixinAccessToken("");} catch (Exception e1) {log.info(e1.getMessage());}// 拼装请求URLdownloadWxFileURL = downloadWxFileURL.replace("MEDIA_ID", serverId).replace("ACCESS_TOKEN", access_token);File wxfile = null;try {wxfile = dowanload(downloadWxFileURL, downloadDir, fileName);} catch (Exception e) {// TODO Auto-generated catch blocklog.info(e.getMessage());} return wxfile; }}

 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。