这是一个java写的获取百度网盘真实下载链接进行下载的程序。
程序里面一些参数拼接是根据浏览器抓包来的。具体的抓包方法网上一大堆,可以参考。这里给出了源码和导出的jar包。
url网址使用于百度分享的地址。暂时没有适配有提取码的地址。

运行的方法:
1、在当前的目录打开cmd,默认不带参数就是用默认的测试的url。
java -jar BaiduPanURL.jar

2、如果想使用自己定义的资源地址可以在后面加一个参数。
java -jar BaiduPanURL.jar your_url

注意:百度网盘同一个ip进行3次下载之后就需要验证码。程序会在当前的目录生成验证码,输入正确的验证码后可以进行下载。

本人亲测有效,百度会限制下载的速率,测试只有100kb左右。

程序源码:
1、GetBaiduCloudRealURL:

    package com.example.download;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;import com.example.bean.Response20;import com.example.bean.SetDataBean;import com.google.gson.Gson;/*** 输入百度网盘的资源地址,获取网盘的真实下载地址。* * @author gaoqiang* */public class GetBaiduCloudRealURL {// 定义一些全局变量private static String url = "https://pan.baidu.com/s/1eQrwbKY";// 资源地址private static String cookie = null;private static final String getvcodeURL = "https://pan.baidu.com/api/getvcode?prod=pan";// 请求vcode地址,不变private static boolean isDownload = true;//标记是否需要下载文件,false就只获取地址private static String server_filename = null;private static String size = null;// 通过浏览器抓包分析,获取百度网盘共享文件的真实下载地址public static void main(String[] args) {if (args.length > 0) {System.out.println("输入的原始地址:" + args[0]);url = args[0];}// 第一次获取cookie()Map<String, String> map1 = HttpUtils.get(url, cookie);System.out.println("服务器返回的cookie:\n" + map1.get("cookie") + "\n");cookie = "PANWEB=1;" + map1.get("cookie").split(";")[0];// 抓包看到携带了PANWEB1,不设置也没问题Map<String, String> params = getBodyParams(map1.get("body"));server_filename = params.get("server_filename");size = params.get("size");// 拼接post的url地址String post_url = getPostUrl(params);// 拼接post携带的参数Map<String, String> data = getPostData(params);// 发送post请求String responseJson = HttpUtils.post(post_url, data, cookie);System.out.println(responseJson + "\n");Gson gson = new Gson();Response20 response20 = gson.fromJson(responseJson, Response20.class);String errorCode = response20.getErrno();int count = 0;while (!errorCode.equals("0") && count < 5) {count++;if (errorCode.equals("-20")) {// 下载超过3次,需要验证码,获取vcode和img地址Map<String, String> generateValidateCode = generateValidateCode(count);data.put("vcode_input", generateValidateCode.get("vcode_input"));data.put("vcode_str", generateValidateCode.get("vcode_str"));String responseJsonCode = HttpUtils.post(post_url, data, cookie);System.out.println(responseJsonCode + "\n");errorCode = gson.fromJson(responseJsonCode, Response20.class).getErrno();if (errorCode.equals("0")) {responseJson = responseJsonCode;}}}if (errorCode.equals("0")) {// 成功返回真实的urlString realURL = parseRealDownloadURL(responseJson);System.out.println("成功!真实的下载链接为:" + realURL);if (isDownload) {System.out.println("正在下载文件...");HttpUtils.download(realURL, cookie, server_filename, size);// 进行下载}else{System.out.println("配置不下载");}} else {System.out.println("尝试了" + count + "次,地址获取失败");}}/*** POST请求的url地址*/public static String getPostUrl(Map<String, String> params) {/*** post请求(抓包可看到) 抓包看到logid,实际测试logid不携带也可以正常抓取* https://pan.baidu.com/api/* sharedownload?sign=2d970c761500085deb09d423d549dea2f4ef28da* &timestamp=* 1515400310&bdstoken=null&channel=chunlei&clienttype=0&web=1* &app_id=250528&logid=MTUxNTQwMDQ1NTc1MTAuOTYwMTE4NzIyMzcxMzYwNQ==*/StringBuffer sb1 = new StringBuffer();sb1.append("https://pan.baidu.com/api/sharedownload?");sb1.append("sign=" + params.get("sign"));sb1.append("&timestamp=" + params.get("timestamp"));sb1.append("&bdstoken=" + params.get("bdstoken"));sb1.append("&channel=chunlei");sb1.append("&clienttype=0");sb1.append("&web=1");sb1.append("&app_id=" + params.get("app_id"));String post_url = sb1.toString();System.out.println("POST请求的网址:" + post_url);return post_url;}/*** 获取POST请求携带的参数*/public static Map<String, String> getPostData(Map<String, String> params) {// POST携带的参数(抓包可看到)Map<String, String> data = new HashMap<String, String>();data.put("encrypt", "0");data.put("product", "share");data.put("uk", params.get("uk"));data.put("primaryid", params.get("primaryid"));// 添加了[],解码就是%5B %5Ddata.put("fid_list", "%5B" + params.get("fid_list") + "%5D");data.put("path_list", "");// 可以不写return data;}/*** 从post返回数据解析出dlink字段,真实的下载地址,这个地址有效期8h*/public static String parseRealDownloadURL(String responseJson) {String realURL = "";Pattern pattern = Pattern.compile("\"dlink\":.*?,");Matcher matcher = pattern.matcher(responseJson);if (matcher.find()) {String tmp = matcher.group(0);String dlink = tmp.substring(9, tmp.length() - 2);realURL = dlink.replaceAll("\\\\", "");}return realURL;}/*** 获取并输入验证码* * @return map{vcode_str:请求的vcode值, vcode_input:输入的验证码}*/public static Map<String, String> generateValidateCode(int count) {// 下载超过3次,需要验证码,获取vcode和img地址Map<String, String> vcodeResponse = HttpUtils.get(getvcodeURL, cookie);String res = vcodeResponse.get("body");System.out.println("获取vcode:" + vcodeResponse.get("body"));Gson gsonVcode = new Gson();Response20 responseVcode = gsonVcode.fromJson(res, Response20.class);String vcode = responseVcode.getVcode();String imgURL = responseVcode.getImg();System.out.println("vcode值:" + vcode);System.out.println("验证码地址:" + imgURL);// 请求验证码HttpUtils.saveImage(imgURL, cookie);System.out.print("查看图片,输入验证码(第" + count + "次尝试/共5次):");InputStreamReader is_reader = new InputStreamReader(System.in);Map<String, String> map = new HashMap<String, String>();try {String result = new BufferedReader(is_reader).readLine();System.out.println("输入的验证码为:" + result + "\n");map.put("vcode_str", vcode);map.put("vcode_input", result);} catch (IOException e) {e.printStackTrace();}return map;}/*** 正则匹配出json字符串,将json字符串转化为java对象。*/public static Map<String, String> getBodyParams(String body) {Map<String, String> map = new HashMap<String, String>();String setData = "";Pattern pattern_setData = Pattern.compile("setData.*?;");Matcher matcher_setData = pattern_setData.matcher(body);if (matcher_setData.find()) {String tmp = matcher_setData.group(0);setData = tmp.substring(8, tmp.length() - 2);// System.out.println("setData:" + setData + "\n");Gson gson = new Gson();SetDataBean bean = gson.fromJson(setData, SetDataBean.class);System.out.println("sign--" + bean.getSign());System.out.println("token--" + bean.getBdstoken());System.out.println("timestamp--" + bean.getTimestamp());System.out.println("uk--" + bean.getUk());System.out.println("shareid--" + bean.getShareid());System.out.println("fs_id--" + bean.getFile_list().getList()[0].getFs_id());System.out.println("file_name--" + bean.getFile_list().getList()[0].getServer_filename());System.out.println("size--" + bean.getFile_list().getList()[0].getSize());System.out.println("app_id--" + bean.getFile_list().getList()[0].getApp_id() + "\n");map.put("sign", bean.getSign());map.put("timestamp", bean.getTimestamp());map.put("bdstoken", bean.getBdstoken());map.put("app_id", bean.getFile_list().getList()[0].getApp_id());map.put("uk", bean.getUk());map.put("shareid", bean.getShareid());map.put("primaryid", bean.getShareid());map.put("fs_id", bean.getFile_list().getList()[0].getFs_id());map.put("fid_list", bean.getFile_list().getList()[0].getFs_id());map.put("server_filename", bean.getFile_list().getList()[0].getServer_filename());map.put("size", bean.getFile_list().getList()[0].getSize());}return map;}}

2、HttpUtils:

    package com.example.download;import java.io.BufferedReader;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;import java.util.HashMap;import java.util.Map;public class HttpUtils {/*** 向指定URL发送GET方法的请求 返回cookie,body等* 会返回流里面的内容,如果下载大文件,需要修改,实时保存,避免内存溢出*/public static Map<String, String> get(String url, String cookie) {BufferedReader in = null;Map<String, String> map = new HashMap<String, String>();try {URL realUrl = new URL(url);// 打开和URL之间的连接URLConnection connection = realUrl.openConnection();// 设置通用的请求属性connection.setRequestProperty("accept", "*/*");connection.setRequestProperty("connection", "Keep-Alive");connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");connection.setConnectTimeout(5000);connection.setReadTimeout(5000);if (null != cookie) {//System.out.println("携带的Cookie:" + cookie);connection.setRequestProperty("Cookie", cookie);}// 建立实际的连接connection.connect();// 定义 BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(connection.getInputStream()));StringBuffer sb = new StringBuffer();String line;while ((line = in.readLine()) != null) {sb.append(line + "\n");//System.out.println("内容:" + line);}String c = connection.getHeaderField("Set-Cookie");map.put("cookie", c);map.put("body", sb.toString());return map;} catch (Exception e) {System.err.println(e.getMessage());} finally {try {if (in != null) {in.close();}} catch (Exception e2) {e2.printStackTrace();}}return null;}/*** 保存验证码*/public static Map<String, String> saveImage(String url, String cookie) {Map<String, String> map = new HashMap<String, String>();InputStream in = null;FileOutputStream fos = null;try {URL realUrl = new URL(url);// 打开和URL之间的连接URLConnection connection = realUrl.openConnection();// 设置通用的请求属性connection.setRequestProperty("accept", "*/*");connection.setRequestProperty("connection", "Keep-Alive");connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");connection.setConnectTimeout(5000);connection.setReadTimeout(5000);if (null != cookie) {connection.setRequestProperty("Cookie", cookie);}// 建立实际的连接connection.connect();in = connection.getInputStream();fos = new FileOutputStream("img.jpeg");int b;while((b= in.read())!=-1){fos.write(b);}return map;} catch (Exception e) {System.err.println(e.getMessage());} finally {try {if (in != null) {in.close();}if(fos != null){fos.close();}} catch (Exception e2) {e2.printStackTrace();}}return null;}static int downloadSize = 0;static boolean isReading = false;//是否在读流,更新进度static long startTime = 0 ;static long endTime = 0 ;/*** 下载文件*/public static Map<String, String> download(String url, String cookie, String filename, final String totalSize) {InputStream in = null;FileOutputStream fos = null;Map<String, String> map = new HashMap<String, String>();try {URL realUrl = new URL(url);// 打开和URL之间的连接URLConnection connection = realUrl.openConnection();// 设置通用的请求属性connection.setRequestProperty("accept", "*/*");connection.setRequestProperty("connection", "Keep-Alive");connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");connection.setConnectTimeout(10000);//          connection.setReadTimeout(5000);if (null != cookie) {connection.setRequestProperty("Cookie", cookie);}// 建立实际的连接connection.connect();in = connection.getInputStream();fos = new FileOutputStream(filename);System.out.println("保存文件名称:" + filename);System.out.println("文件总大小:" + totalSize);//利用字符数组读取流数据startTime = System.currentTimeMillis();//每隔1s读一次数据new Thread(){@Overridepublic void run() {String total = UnitSwitch.formatSize(Long.parseLong(totalSize));StringBuffer sb = new StringBuffer();for (int i = 0; i < 20; i++) {sb.append("\b");}while(isReading){endTime = System.currentTimeMillis();String speed = UnitSwitch.calculateSpeed(downloadSize, endTime-startTime);System.out.println(UnitSwitch.formatSize(downloadSize) + "/" + total + ",平均下载速率:" + speed);try {sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}}}.start();isReading = true;int len;byte[] arr = new byte[1024 * 8];while((len = in.read(arr)) != -1) {fos.write(arr, 0, len);downloadSize += len;}endTime = System.currentTimeMillis();String speed = UnitSwitch.calculateSpeed(downloadSize, endTime-startTime);String total = UnitSwitch.formatSize(Long.parseLong(totalSize));System.out.println(UnitSwitch.formatSize(downloadSize) + "/" + total + ",平均下载速率:" + speed);System.out.println("下载完成,总耗时:" + (endTime - startTime)/1000 + "秒");return map;} catch (Exception e) {System.err.println(e.getMessage());} finally {isReading = false;try {if (in != null) {in.close();}if(fos != null){fos.close();}} catch (Exception e2) {e2.printStackTrace();}}return null;}/*** 发送HttpPost请求* * @param strURL*            服务地址* @param params* * @return 成功:返回json字符串<br/>*/public static String post(String strURL, Map<String, String> params, String cookie) {try {URL url = new URL(strURL);// 创建连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setDoInput(true);connection.setUseCaches(false);connection.setInstanceFollowRedirects(true);connection.setRequestMethod("POST"); // 设置请求方式connection.setRequestProperty("Accept", "*/*"); // 设置接收数据的格式connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // 设置发送数据的格式if (null != cookie) {System.out.println("携带的Cookie:" + cookie);connection.setRequestProperty("Cookie", cookie);}connection.connect();OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码StringBuffer sb = new StringBuffer();for (String s : params.keySet()) {sb.append(s + "=" + params.get(s) + "&");}System.out.println("携带的参数:" + sb.toString().substring(0, sb.length() - 1));out.append(sb.toString().substring(0, sb.length() - 1));out.flush();out.close();int code = connection.getResponseCode();BufferedReader in = null;if (code == 200) {in = new BufferedReader(new InputStreamReader(connection.getInputStream()));} else {in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));}System.out.println("响应码:" + code);// 定义BufferedReader输入流来读取URL的响应String line;StringBuffer sb1 = new StringBuffer();while ((line = in.readLine()) != null) {sb1.append(line);}return sb1.toString();} catch (IOException e) {System.err.println(e.getMessage());return "error";}}}

3、UnitSwitch:

package com.example.download;
import java.text.DecimalFormat;
public class UnitSwitch {/*** 处理文件大小*/public static String formatSize(long size) {DecimalFormat fnum = new DecimalFormat("##0.0");String result;if (size > (1024 * 1024 * 1024)) {result = fnum.format((size / ((float) (1024 * 1024 * 1024)))) + "GB";}else if (size > (1024 * 1024)) {result = fnum.format((size / ((float) (1024 * 1024)))) + "MB";} else if (size > 1024) {result = fnum.format((float) size / ((float) 1024)) + "KB";} else {result = String.valueOf((int) size) + "B";}return result;}/*** @author gaoqiang*         <p>*         计算网络速率*         <p>*         返回的格式 Kb/s* @param delta*            : 传入一个Bytes数据* @param duration_time*            : 下载delta数据所需要用的时间* @return*/public static String calculateSpeed(long delta, long duration_time) {DecimalFormat fnum = new DecimalFormat("##0.0");String speedStr;float speed = ((float) delta * 1000 / (float) (duration_time));// 毫秒转换if (speed > (1024 * 1024)) {speedStr = fnum.format((speed / ((float) (1024 * 1024)))) + "M/s";} else if (speed > 1024) {speedStr = fnum.format((float) speed / ((float) 1024)) + "K/s";} else {speedStr = String.valueOf((int) speed) + "B/s";}return speedStr;}
}

4、Response20:

    package com.example.bean;/*** 服务器返回的json,转java对象* 错误码为20 代表需要验证码* @author gaoqiang**/public class Response20 {String errno;String request_id;String server_time;String vcode;String img;public String getErrno() {return errno;}public void setErrno(String errno) {this.errno = errno;}public String getRequest_id() {return request_id;}public void setRequest_id(String request_id) {this.request_id = request_id;}public String getServer_time() {return server_time;}public void setServer_time(String server_time) {this.server_time = server_time;}public String getVcode() {return vcode;}public void setVcode(String vcode) {this.vcode = vcode;}public String getImg() {return img;}public void setImg(String img) {this.img = img;}}

5、SetDataBean:

    package com.example.bean;public class SetDataBean {private String sign;private String timestamp;private String bdstoken;private String uk;private String shareid;private FileList file_list;public String getSign() {return sign;}public void setSign(String sign) {this.sign = sign;}public String getTimestamp() {return timestamp;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public String getBdstoken() {return bdstoken;}public void setBdstoken(String bdstoken) {this.bdstoken = bdstoken;}public String getUk() {return uk;}public void setUk(String uk) {this.uk = uk;}public String getShareid() {return shareid;}public void setShareid(String shareid) {this.shareid = shareid;}public FileList getFile_list() {return file_list;}public void setFile_list(FileList file_list) {this.file_list = file_list;}public static class FileList {String errno;List[] list;public String getErrno() {return errno;}public void setErrno(String errno) {this.errno = errno;}public List[] getList() {return list;}public void setList(List[] list) {this.list = list;}}public static class List {String app_id;String fs_id;String server_filename;String size;public String getApp_id() {return app_id;}public void setApp_id(String app_id) {this.app_id = app_id;}public String getFs_id() {return fs_id;}public void setFs_id(String fs_id) {this.fs_id = fs_id;}public String getServer_filename() {return server_filename;}public void setServer_filename(String server_filename) {this.server_filename = server_filename;}public String getSize() {return size;}public void setSize(String size) {this.size = size;}}}

6、运行的截图:

运行的参数图:

效果图:

亲测有效。百度网盘请求的参数可能会变,但是方法不会变。通过浏览器抓包就可以分析修改。
工程源码下载地址:http://download.csdn.net/download/gaopinqiang/10197336

获取百度网盘下载真实地址相关推荐

  1. JAVA获取百度网盘下载真实地址

    这是一个java写的获取百度网盘真实下载链接进行下载的程序.  程序里面一些参数拼接是根据浏览器抓包来的.具体的抓包方法网上一大堆,可以参考.这里给出了源码和导出的jar包.  url网址使用于百度分 ...

  2. 千方百计获取百度网盘下载链接

    千方百计获取百度网盘下载链接 重要的事情说三遍: 高手勿喷! 高手勿喷! 高手勿喷! 以前看过一篇帖子是在手机上获取百度云的下载链接然后在发送到电脑上, 这样的话百度云后台会判定为两次请求, 请求同一 ...

  3. IDM下载百度网盘文件,获取百度网盘文件url地址,破解

    下面是谷歌插件,你用这个里面的谷歌进入百度网盘,会有一个显示百度网盘文件链接选项,复制这个链接到IDM就可以了. 链接:https://pan.baidu.com/s/1B0C-VyWvf7xc5Y1 ...

  4. 怎样获取百度网盘下载链接

    百度网盘限速和会员限制一直是我们头疼的问题,所以今天我就来推荐一款神器tampermonkey.下面我就来说一下详细的步骤. 1.下载油猴 tampermonkey据说运行的时候有点占内存,楼主自己不 ...

  5. 百度网盘——下载限速问题解决方案(油猴(Tampermonkey)+百度网盘直链下载助手+IDM)

    一.基本概念 Tampermonkey(油猴):Tampermonkey插件是一个免费的浏览器扩展和最为流行的用户脚本管理器,拥有适用于 Chrome, Microsoft Edge, Safari, ...

  6. IDM下载器使用方法详解:百度网盘下载,视频会员一网打尽!

    idm是海内外都非常受欢迎的一款下载管理软件.它支持视频媒体嗅探和多线程下载,能够完美替代谷歌Chrome浏览器.Edge浏览器等浏览器的原生下载功能.在浏览器中单击下载链接时,idm将接管浏览器的原 ...

  7. Qt安装包百度网盘下载分享

    君君最近看到比较多留言就是,Qt安装包下载不了.好吧,盘它!991个Qt安装包,共563G大小. 怎么获取呢?   Qt君公众号回复"Qt安装包"或回复"991" ...

  8. Java百度网盘创建链接,java获取百度网盘真实下载链接的方法

    本文实例讲述了java获取百度网盘真实下载链接的方法.分享给大家供大家参考.具体如下: 目前还存在一个问题,同一ip在获取3次以后会出现验证码,会获取失败,感兴趣的朋友对此可以加以完善. 返回的Lis ...

  9. python 百度网盘库 根据文件名获取网盘链接_GitHub - tychxn/baidu-wangpan-parse: 获取百度网盘分享文件的下载地址...

    百度网盘分享文件下载链接解析 功能 获取百度网盘分享文件的真实下载地址 将获取到的下载链接复制到IDM.FDM等下载器即可实现高速下载,避免使用百度网盘客户端 运行环境 Python3 (兼容Pyth ...

最新文章

  1. ctf xor题_从一道CTF题目谈PHP中的命令执行
  2. CentOS安装sshd服务
  3. idrmyimage 技巧_王者荣耀公孙离2000场-心得技巧,教你究极进阶!
  4. sql SERVER 模拟试题
  5. django model 数据类型
  6. webapp文本编辑器_Project Student:维护Webapp(可编辑)
  7. 使用ArrayList时设置初始容量的重要性
  8. mysql的安装备份恢复_安装使用Percona XtraBackup来备份恢复MySQL的教程
  9. 解决 PL/SQL Oracle错误:ORA-01033
  10. 布丰投针java实现,MATLAB模拟布丰投针实验
  11. linux防火墙应用,Linux防火墙iptables基本应用
  12. MySQL之四种SQL性能分析工具
  13. Perl脚本使用小总结
  14. matlab曲线导入cad,MATLAB导入CAD数据
  15. Matlab绘图相关参数备忘录
  16. unity中使用C#语言判断斗地主出牌牌型
  17. 2012年秋季,斯皮维大厅音乐会的亮点
  18. python股票网格交易法详解_详解网格交易法
  19. PCB模拟信号线与数字信号线布线技巧
  20. eclipse怎么搜索关键字? eclipse查找关键字的技巧

热门文章

  1. tpl怎么口_解决tplogin.cn打开是电信登录页面的办法是什么?
  2. 正则表达式-Java实现 - \d、\D、\w、\W、+、*、?
  3. 利用python进行体重指数计算
  4. 神笔马良——基于 OpenGL 的涂鸦框架
  5. 出现Expected to return a value in arrow function.问题解决方法
  6. 配电自动化终端安防改造用配电加密模块(产品已经在10KV线路上数千台配电自动化终端进行过安防改造)...
  7. 苏州大学文正学院JAVA试卷_苏州大学文正学院试题库建设管理办法(试行)
  8. native react 图片多选_react-native实现的多图片选择器
  9. 第 4-2 课:开发一个 Flutter TV 应用
  10. IE起始页被改为 http://www.537.com 的解决