java做个系统文件下载_通过Java代码,模拟登陆,下载其系统的文件

Java代码下载其他系统的文件时,需要有:登陆链接、密码、账户和下载链接;

在登陆之时,需要对url进行转码,使得后台提交不能出现乱码(根据自身实际情况进行设置转码格式)。只需要每次请求携带cookie值,并且将请求参数携带即可,如下案例下载时有token需要将值携带才可进行下载

import org.apache.commons.codec.binary.Base64;

import org.apache.commons.httpclient.Cookie;

import org.apache.commons.httpclient.Header;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.NameValuePair;

import org.apache.commons.httpclient.cookie.CookiePolicy;

import org.apache.commons.httpclient.methods.PostMethod;

import org.apache.commons.httpclient.params.HttpMethodParams;

import org.apache.commons.io.IOUtils;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESKeySpec;

import java.io.*;

import java.net.URLDecoder;

import java.net.URLEncoder;

import java.security.SecureRandom;

import java.text.SimpleDateFormat;

import java.util.Date;

/**

* 文件导出

*/

public class FileExport {

public static void main(String[] args) {

try {

//文件存储路径

String Filepath = "E:/resource/";

FileExport r = new FileExport();

//r.prjectInfoExp(Filepath);

r.dingdanExcel(Filepath);

} catch (Exception e) {

}

}

/**

* @param Filepath 文件导出路径

*/

public void prjectInfoExp(String Filepath) {

//获取加密key

String saltUrl = "http://127.0.0.1:20000/uac_oa/getSalt?r=" + Math.random();

// 登陆 Url

String loginUrl = "https://127.0.0.1/doPrevLogin?r=" + Math.random();

//获取token

String tokenUrl = "http://127.0.0.1/ssoModule?appId=CHNTPMS&appAcctId=432805";

//下载链接

String dataUrl = "http://127.0.0.1:27183/pmsexport/cn.chinatowercom.pms.sso.ssoAuth.flow?isNewbusiness=&pro_manager=&siteId=&ifDivideDes=&ifDivideSupvis=";

//创建协议

HttpClient httpClient = new HttpClient();

//设置编码格式

httpClient.getParams().setContentCharset("UTF-8");

httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

// 设置 HttpClient 接收 Cookie,用与浏览器一样的策略

httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

try {

/************获取加密key***********/

//进行请求获取加密key

PostMethod postSalt = new PostMethod(saltUrl);

//发起请求

int statusCode = httpClient.executeMethod(postSalt);

//获取到加密key

String salt = postSalt.getResponseBodyAsString().replace("\"", "");

/************登录***********/

System.out.println("登录。。。");

//加密后的账户和密码

String username = encode("zhaolf3", salt);

String password = encode("Lizzard2018", salt);

// 设置登录请求参数

NameValuePair[] data = {

new NameValuePair("csrftoken", ""),

new NameValuePair("username", username),

new NameValuePair("password", password),

new NameValuePair("remember", "true"),

new NameValuePair("rememberPwd", "false"),

new NameValuePair("loginFrom", "oa"),

new NameValuePair("fp", "8d6b2e0dffb43ce2d1ee5855cc83946f"),

new NameValuePair("useragent", "Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64;+rv:66.0)+Gecko/20100101+Firefox/66.0")};

//登录请求

PostMethod postLogin = new PostMethod(loginUrl);

//加入请求参数

postLogin.setRequestBody(data);

//发起登录请求

httpClient.executeMethod(postLogin);

// 获得登陆后的 Cookie

StringBuffer tmpcookieLogin = new StringBuffer();

Cookie[] cook = httpClient.getState().getCookies();

for (Cookie c : cook) {

tmpcookieLogin.append(c.toString() + ";");

//System.out.println("cookies = " + c.toString());

}

/************获取跳转所需的token***********/

System.out.println("获取跳转所需的token。。。");

PostMethod postToken = new PostMethod(tokenUrl);

postToken.setRequestHeader("cookie", tmpcookieLogin.toString());

httpClient.executeMethod(postToken);

// 获得登陆后的 Cookie

StringBuffer cookieToken = new StringBuffer();

Cookie[] cook_1 = httpClient.getState().getCookies();

for (Cookie c : cook_1) {

cookieToken.append(c.toString() + ";");

//System.out.println("cookies = " + c.toString());

}

//获取到Token

String token = postToken.getResponseBodyAsString().split("token=")[1].split("&")[0];

/************进行下载文件信息文件***********/

System.out.println("下载文件。。。");

long startTime = System.currentTimeMillis();

// 进行下载请求

PostMethod postMethos = new PostMethod(bianma(dataUrl + "&token=" + token));

// 每次访问需授权的网址时需带上前面的 cookie 作为通行证

postMethos.setRequestHeader("cookie", cookieToken.toString());

postMethos.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/66.0");

//文件接收类型

postMethos.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

postMethos.setRequestHeader("Content-Type", "text/html; charset=UTF-8");

postMethos.setRequestHeader("Accept-Encoding", "gzip, deflate");

httpClient.executeMethod(postMethos);

//设置下载文件名称

SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

String fileName = "*********" + format.format(new Date()) + ".xlsx";

Header[] headers = postMethos.getResponseHeaders();

InputStream inputStream = postMethos.getResponseBodyAsStream();

//将输出流转换问字节

byte[] getData = readInputStream(inputStream);

//存储文件名称

File file = new File(Filepath + File.separator + fileName);

FileOutputStream fos = new FileOutputStream(file);

//将字节输出到文件中

fos.write(getData);

long endTime = System.currentTimeMillis();

System.out.println("文件下载所需时间:" + (endTime - startTime));

if (inputStream != null) {

inputStream.close();

}

if (fos != null) {

fos.close();

}

if (inputStream != null) {

inputStream.close();

}

System.out.println("info:下载成功");

} catch (Exception e) {

e.printStackTrace();

System.out.println("info:下载失败");

}

}

/**

* 从输入流中获取字节数组

*

* @param inputStream

* @return

* @throws IOException

*/

public static byte[] readInputStream(InputStream inputStream) throws IOException {

byte[] buffer = new byte[1024];

int len = 0;

ByteArrayOutputStream bos = new ByteArrayOutputStream();

while ((len = inputStream.read(buffer)) != -1) {

bos.write(buffer, 0, len);

}

bos.close();

return bos.toByteArray();

}

/**

* url进行转码 防止有中文在出现乱码

*

* @param url

* @return

*/

public static String bianma(String url) {

//被转码后的url

String result = "";

//需要转码的url

int index = url.indexOf("?");

result = url.substring(0, index + 1);

String temp = url.substring(index + 1);

try {

//URLEncode转码会将& : / = 等一些特殊字符转码,(但是这个字符 只有在作为参数值 时需要转码;例如url中的&具有参数连接的作用,此时就不能被转码)

String encode = URLEncoder.encode(temp, "utf-8");

System.out.println(encode);

encode = encode.replace("%3D", "=");

encode = encode.replace("%2F", "/");

encode = encode.replace("+", "%20");

encode = encode.replace("%26", "&");

result += encode;

return result;

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return result;

}

/**

* DES加密

*

* @param datasource 为加密字符

* @param key 密钥key

* @return

*/

public String encode(String datasource, String key) {

try{

SecureRandom random = new SecureRandom();

DESKeySpec desKey = new DESKeySpec(key.getBytes());

//创建一个密匙工厂,然后用它把DESKeySpec转换成

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

SecretKey securekey = keyFactory.generateSecret(desKey);

//Cipher对象实际完成加密操作

Cipher cipher = Cipher.getInstance("DES");

//用密匙初始化Cipher对象

cipher.init(Cipher.ENCRYPT_MODE, securekey, random);

//现在,获取数据并加密

byte[] temp = Base64.encodeBase64(cipher.doFinal(datasource.getBytes()));

return IOUtils.toString(temp, "UTF-8");

} catch (Throwable e) {

e.printStackTrace();

return null;

}

}

/**

* DES解密

*

* @return

*/

public String decode(String src, String key) throws Exception {

// DES算法要求有一个可信任的随机数源

SecureRandom random = new SecureRandom();

// 创建一个DESKeySpec对象

DESKeySpec desKey = new DESKeySpec(key.getBytes());

// 创建一个密匙工厂

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

// 将DESKeySpec对象转换成SecretKey对象

SecretKey securekey = keyFactory.generateSecret(desKey);

// Cipher对象实际完成解密操作

Cipher cipher = Cipher.getInstance("DES");

// 用密匙初始化Cipher对象

cipher.init(Cipher.DECRYPT_MODE, securekey, random);

// 真正开始解密操作

return IOUtils.toString(cipher.doFinal(Base64.decodeBase64(src.getBytes())), "UTF-8");

}

}

标签:Java,String,代码,System,Cipher,import,encode,new,模拟

来源: https://blog.csdn.net/weixin_43525290/article/details/89241439

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值