java 对接腾讯COS实现下载文件

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.region.Region;
import com.wqh.fsrm.common.util.DateUtils;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CosDownloadUtil {

    public static final String secretId = "AKIDC9xVnoZv4vWyiByPM5XjlW0TglcBdaR1";
    public static final String secretKey = "g6KKBn8JDqCRSDKJcePt63jhOs87q65n";
    public static final String bucket = "polz-files-1302700757";
    public static final String regionString = "ap-shanghai";
    public static final String url = "https://polz-files-1302700757.cos.ap-shanghai.myqcloud.com";

    public static COSClient getCOSClient(){
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(regionString);
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    public void getZipFile(HttpServletResponse response, HttpServletRequest request) {
        String fileKeys = request.getParameter("fileKeys");
        if (null == fileKeys || fileKeys.length() == 0) {
            return;
        }
        String[] keys = fileKeys.split(",");
        if (keys == null || keys.length <= 0) {
            return;
        }
        try {
            // 初始化
            COSClient cosClient = getCOSClient();

            String times = DateUtils.generateTimestampNo();
            String fileName = times.concat(".zip");

            // 创建临时文件
            java.io.File zipFile = java.io.File.createTempFile(times, ".zip");
            FileOutputStream f = new FileOutputStream(zipFile);
            /**
             * 作用是为任何OutputStream产生校验和
             * 第一个参数是制定产生校验和的输出流,第二个参数是指定Checksum的类型 (Adler32(较快)和CRC32两种)
             */
            CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
            // 用于将数据压缩成Zip文件格式
            ZipOutputStream zos = new ZipOutputStream(csum);
            for (String key : keys) {
                File file = new File(key);
                String mimeType = URLConnection.guessContentTypeFromName(file.getName());
                InputStream inputStream = null;
                if ("mp4".equals(mimeType)) {    //如果是mp4 格式需要直接从服务器上下载
                    HttpURLConnection httpURLConnection = null;
                    URL url = new URL(key);
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    // 设置网络连接超时时间
                    httpURLConnection.setConnectTimeout(3000);
                    // 设置应用程序要从网络连接读取数据
                    httpURLConnection.setDoInput(true);
                    httpURLConnection.setRequestMethod("GET");
                    int responseCode = httpURLConnection.getResponseCode();
                    if (responseCode == 200) {
                        // 从服务器返回一个输入流
                        inputStream = httpURLConnection.getInputStream();
                    }
                } else {
                    //m.setFileUrl(hoeOssUrl + m.getFileUrl());
                    COSObject cosObject = cosClient.getObject(bucket, key);
                    inputStream = cosObject.getObjectContent();
                }
                // 对于每一个要被存放到压缩包的文件,都必须调用ZipOutputStream对象的putNextEntry()方法,确保压缩包里面文件不同名
                if (null == key || key.length() == 0) {
                    continue;
                }
                int len = key.split("/").length;
                zos.putNextEntry(new ZipEntry(key.split("/")[len - 1]));


                int bytesRead = 0;
                // 向压缩文件中输出数据
                while ((bytesRead = inputStream.read()) != -1) {
                    zos.write(bytesRead);
                }
                inputStream.close();
                zos.closeEntry(); // 当前文件写完,定位为写入下一条项目
            }
            zos.close();
            String header = request.getHeader("User-Agent").toUpperCase();
            if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                fileName = URLEncoder.encode(fileName, "utf-8");
                fileName = fileName.replace("+", "%20");    //IE下载文件名空格变+号问题
            } else {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            }
            response.reset();
            response.setContentType("text/plain");
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Location", fileName);
            response.setHeader("Cache-Control", "max-age=0");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            FileInputStream fis = new FileInputStream(zipFile);
            BufferedInputStream buff = new BufferedInputStream(fis);
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            byte[] car = new byte[1024];
            int l = 0;
            while (l < zipFile.length()) {
                int j = buff.read(car, 0, 1024);
                l += j;
                out.write(car, 0, j);
            }
            // 关闭流
            fis.close();
            buff.close();
            out.close();

            cosClient.shutdown();
            // 删除临时文件
            zipFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

### Java 腾讯云 发送短信 示例代码 为了使用Java调用腾讯云的服务来发送短信,开发者需要先完成一些准备工作,包括但不限于注册腾讯云账号并创建相应的短信应用以获取必要的配置信息如`SmsSdkAppId`等[^2]。 下面是一个基于腾讯云官方API文档提供的Java示例外例,该例子展示了怎样构建请求以及执行发送操作: ```java import com.qcloud.cos.auth.BasicCOSCredentials; import com.qcloud.cos.auth.COSCredentials; import com.qcloud.cos.exception.CosClientException; import com.qcloud.cos.http.HttpMethodName; import com.qcloud.cos.region.Region; import com.qcloud.cos.utils.JsonUtils; import com.tencentcloudapi.common.Credential; import com.tencentcloudapi.common.profile.ClientProfile; import com.tencentcloudapi.common.profile.HttpProfile; import com.tencentcloudapi.sms.v20210111.SmsClient; import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest; import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse; public class TencentCloudSMS { public static void main(String[] args) { try { // 初始化客户端配置 Credential cred = new Credential("SECRET_ID", "SECRET_KEY"); HttpProfile httpProfile = new HttpProfile(); httpProfile.setEndpoint("sms.tencentcloudapi.com"); ClientProfile clientProfile = new ClientProfile(); clientProfile.setHttpProfile(httpProfile); SmsClient smsClient = new SmsClient(cred, "", clientProfile); SendSmsRequest req = new SendSmsRequest(); req.setPhoneNumberSet(new String[]{"+86137xxxxxxxx"}); // 替换成实际电话号码 req.setTemplateID("123456"); // 使用自己的模板 ID req.setSmsSdkAppid("sdkappid"); // SDK App ID 是在 SMS 控制台申请的 APPID req.setSign("签名名称"); // 签名内容不是签名 ID req.setTemplateParamSet(new String[]{"code"}); // 如果有参数则填入相应位置 SendSmsResponse resp = smsClient.SendSms(req); System.out.println(SendSmsResponse.toJsonString(resp)); } catch (CosClientException e) { e.printStackTrace(); } } } ``` 上述代码片段中包含了几个关键点需要注意: - `Credential`对象用于存储用户的密钥信息; - `SendSmsRequest`类实例化时设置的目标手机号码、使用的模板编号以及其他必要字段; - 成功发送后会返回一个包含状态和其他响应详情的对象; 此段程序实现了向指定手机发送一条带有验证码的消息的功能。当然,在真实环境中还需要处理异常情况,并确保所有的敏感数据都得到了妥善保护[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浮生若梦01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值