java http请求

---------------------------1接口请求----------------------------------------

/**
     * 定义编码格式 UTF-8
     */
    public static final String URL_PARAM_DECODECHARSET_UTF8 = "UTF-8";

    /**
     * 定义编码格式 GBK
     */
    public static final String URL_PARAM_DECODECHARSET_GBK = "GBK";

    private static final String URL_PARAM_CONNECT_FLAG = "&";

    private static final String EMPTY = "";

    private static MultiThreadedHttpConnectionManager connectionManager = null;

    private static int connectionTimeOut = 25000;

    private static int socketTimeOut = 25000;

    private static int maxConnectionPerHost = 20;

    private static int maxTotalConnections = 20;

    private static HttpClient client;
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    /**
     * 执行一个HTTP POST请求,返回请求响应的HTML
     *
     * @param url         请求的URL地址
     * @param params    请求的查询参数,能够为null
     * @param charset 字符集
     * @param pretty    是否美化
     * @return 返回请求响应的HTML
     */
    public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) {
        StringBuffer response = new StringBuffer();
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        //设置参数的字符集
        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,charset);
        //设置Http Post数据
        if (params != null) {
            //HttpMethodParams p = new HttpMethodParams();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                //p.setParameter(entry.getKey(), entry.getValue());
                method.setParameter(entry.getKey(), entry.getValue());
            }
            //method.setParams(p);
        }
        try {
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
                String line;
                while ((line = reader.readLine()) != null) {
                    if (pretty)
                        response.append(line).append(System.getProperty("line.separator"));
                    else
                        response.append(line);
                }
                reader.close();
            }
        } catch (IOException e) {
            logger.error("执行HTTP Post请求" + url + "时,发生异常!", e);
        } finally {
            method.releaseConnection();
        }
        return response.toString();
    }

-----------------------2SFTP附件下载  SFTPUtil.java文件在当前根目录-----------------------------

/**
     * 获取ip地址
     * 1.传入参数ip地址
     * 2.根据ip地址下载文件
     * 3.并把文件上传到h3c文件服务器
     * 4.获取新的ip
     *
     * @return
     */
    @SneakyThrows
    @Override
    public Boolean uploadIpAddress() {
        log.error("-----------------------附件拉取开始-----------------------");
        int startId=1;
        int endId=1;
        //查询文件表最大id
        QueryWrapper<MatFile> matFileMaxQueryWrapper = new QueryWrapper<>();
        matFileMaxQueryWrapper.lambda().select(MatFile::getId);
        matFileMaxQueryWrapper.lambda().orderByDesc(MatFile::getId);
        matFileMaxQueryWrapper.last(" limit 1 ");
        MatFile matFileMax=new MatFile().selectOne(matFileMaxQueryWrapper);
        if(matFileMax!=null&&matFileMax.getId()!=null){
            endId=matFileMax.getId().intValue();
        }
        //查询ftp表最大id
        QueryWrapper<MatSftpFileMax> matSftpFileMaxQueryWrapper = new QueryWrapper<>();
        matSftpFileMaxQueryWrapper.lambda().select(MatSftpFileMax::getMatFileId);
        matSftpFileMaxQueryWrapper.lambda().orderByDesc(MatSftpFileMax::getMatFileId);
        matSftpFileMaxQueryWrapper.last(" limit 1 ");
        MatSftpFileMax matSftpFileMax=new MatSftpFileMax().selectOne(matSftpFileMaxQueryWrapper);
        if(matSftpFileMax!=null&&matSftpFileMax.getMatFileId()!=null){
            startId=matSftpFileMax.getMatFileId().intValue();
        }
        for (int j = startId; j <= endId; j++) {
            System.out.println("**********开始处理编号为" + j + "的matFile表id的数据**********");
            Long id = Long.parseLong(Integer.valueOf(j).toString());
            QueryWrapper<MatFile> matFileQueryWrapper = new QueryWrapper<>();
            matFileQueryWrapper.lambda().select(MatFile::getId, MatFile::getFileAddr, MatFile::getFileName);
            matFileQueryWrapper.lambda().isNotNull(MatFile::getFileAddr);
            matFileQueryWrapper.lambda().ne(MatFile::getFileAddr, "");
            matFileQueryWrapper.lambda().like(MatFile::getFileAddr, "http");
            matFileQueryWrapper.lambda().eq(MatFile::getId, id);
            MatFile temp = new MatFile().selectOne(matFileQueryWrapper);
            Calendar now = Calendar.getInstance();
            //今天上次的文件夹
            String nowYearMonth = now.get(Calendar.YEAR) + ((now.get(Calendar.MONTH) + 1 < 10) ? "0"
                    + (now.get(Calendar.MONTH) + 1) : "" + (now.get(Calendar.MONTH) + 1))
                    + ((now.get(Calendar.DAY_OF_MONTH) < 10) ? "0" + (now.get(Calendar.DAY_OF_MONTH)) : ""
                    + (now.get(Calendar.DAY_OF_MONTH)));

            if (temp != null) {
                String fileAddr = temp.getFileAddr();
                List<MatSftpFile> matSftpFiles = baseMapper.selectList(new LambdaQueryWrapper<MatSftpFile>()
                        .eq(MatSftpFile::getMatFileAddr, fileAddr)
                        .select(MatSftpFile::getId));
                if (matSftpFiles == null || matSftpFiles.size() == 0) {
                    String content = "";
                    MatSftpFileLog matSftpFileLog = new MatSftpFileLog();
                    MatSftpFile matSftpFile = new MatSftpFile();
                    int i = temp.getFileName().lastIndexOf(StrUtil.DOT);
                    String lastFileName = temp.getFileName().substring(i + 1);
                    //生成文件名称
                    String fileName = IdUtil.simpleUUID() + StrUtil.DOT + lastFileName;
                    String newFileUrl = "";
                    try {
                        //获取当前url的文件流
                        URL url = new URL(temp.getFileAddr());
                        // 获取连接
                        URLConnection conn = url.openConnection();
                        // 重新获取流
                        InputStream input = conn.getInputStream();
                        //填写服务器信息,登录服务器
                        SFTPUtil sftp = new SFTPUtil(sftpUserName, sftpPassword, sftpHost, sftpPort);
                        //sftp服务器登录
                        sftp.login();
                        //sftp服务器上传
                        sftp.upload(ftpPath, "/" + nowYearMonth, fileName, input);
                        newFileUrl = "http://" + sftpHost + ":" + sftpShowPort + "/" + nowYearMonth + "/" + fileName;
                        //sftp服务器推出并关闭流
                        sftp.logout();
                        input.close();
                    } catch (FileNotFoundException e) {
                        logger.error("------没有找到-----:" + fileName + "文件");
                        content = "没有找到当前文件";
                        e.printStackTrace();
                    } catch (SocketException e) {
                        logger.error("连接FTP失败.");
                        content = "连接FTP服务器失败";
                        e.printStackTrace();
                    } catch (IOException e) {
                        logger.error("文件读取错误.");
                        content = "文件读取失败";
                        e.printStackTrace();
                    } finally {
                        if (StringUtils.isNotBlank(content)) {
                            matSftpFileLog.setMatFileId(temp.getId());
                            matSftpFileLog.setMatFileName(temp.getFileName());
                            matSftpFileLog.setMatFileAddr(temp.getFileAddr());
                            matSftpFileLog.setContent(content);
                            matSftpFileLogService.save(matSftpFileLog);
                        }

                    }
                    matSftpFile.setMatFileId(temp.getId());
                    matSftpFile.setMatFileAddr(temp.getFileAddr());
                    matSftpFile.setMatFileTime(temp.getModifyTime());
                    matSftpFile.setFileName(temp.getFileName());
                    matSftpFile.setFileAddr(newFileUrl);
                    matSftpFile.setNfileName(fileName);
                    this.save(matSftpFile);
                }
            }
            MatSftpFileMax fileMax=new MatSftpFileMax();
            fileMax.setMatFileId(Long.valueOf(j));
            matSftpFileMaxService.save(fileMax);
            System.out.println("**********结束处理编号为" + j + "的matFile表id的数据**********");
        }
        log.error("-----------------------附件拉取结束-----------------------");
        return Boolean.TRUE;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值