package com.zzsn.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/*
使用rpc调用aria2c.exe进行视频下载
aria2c.exe --conf-path=./aria2.conf
该方法使用了aria2c的方式对图片，视频，音频进行下载保存到相应的目录中
 */
public class FileDownloadUtil {
    public static void main(String[] args) {
        sendDownloadInfo("1111","http://www.csicl.com.cn/n332/n335/c22950/part/27649.png",
                "https://www.bilibili.com/video/BV1xK4y1x7D9?p=2","aa","aa.png");
    }

    /**
     *
     * @param id 资讯id
     * @param url 文件链接
     * @param referer 网站地址
     * @param path  文件下载路径
     * @param vname  下载保存的文件名
     */
    public static void sendDownloadInfo(String id,String url,String referer,String path,String vname ){
        String param="{\"jsonrpc\": \"2.0\", \"id\": \""+id+"\", \"method\": \"aria2.addUri\","
                + "\"params\": [[\""+url+"\"], {\"referer\":\""+referer+"\" , \"dir\": \""+path+"\",\"out\":\""+vname+"\"}]}";
        sendPost_body("http://localhost:6800/jsonrpc",param);
    }

    public static String sendPost_body(String arl, String s) {

        // 创建url资源
        OutputStreamWriter out = null;
        URL url;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        System.out.println("请求地址:"+arl);
        try {
            url = new URL(arl);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            return "";
        }
        try {
            // 建立http连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置允许输出
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置传递方式
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestMethod("POST"); // 设置请求方式
            conn.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            conn.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");//设置消息头，解决508错误
//   		conn.setConnectTimeout(1000*60*10);
//   		conn.setReadTimeout(1000*60*10);
            // 开始连接请求
            conn.connect();
            out = new OutputStreamWriter(conn.getOutputStream(), "utf-8"); // utf-8编码
            // 写入请求的字符串
            out.append(s);
            out.flush();
            out.close();
            System.out.println(s);
            if(conn.getResponseCode()==200){
                // System.out.println("success");
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
            }

        } catch (Exception e) {
            // System.out.println("发送 POST 请求出现异常！" + e);
            String body="";
            e.printStackTrace();
            // log.error("远程服务未开启", e);
//   		result.append("");
            return body;
        }finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("发送 POST 请求结果数据" + result.toString());
        return result.toString();

    }
}
