Java HttpCliet模拟用户登录并保持会话下载文件

本文介绍了一个Java HTTP工具类的实现,包括模拟表单登录和从指定URL下载文件到本地的功能。通过HttpClient执行POST请求进行登录,并在登录成功后使用GET请求下载资源。
public class HttpUtil {
	public static HttpClient client = null;
/**
	 * 登录成功下载
	 * @param loginUrl 登录地址
	 * @param data 表单值的map
	 * @param downloadurl 下载路径
	 * @param path 本地存放路径
	 * @return
	 */
	public static String download(String loginUrl,Map<String, String> data,String downloadurl,String path) {
		login(loginUrl, data);	
		GetMethod get = new GetMethod(downloadurl);		
		FileOutputStream outputStream = null;		
		try {
			int i = client.executeMethod(get);
			if("200".equals(i)) {
				outputStream = new FileOutputStream(path);
				outputStream.write(get.getResponseBody());
			}else{
				client = null;
				loginNh(loginUrl, data);
				client.executeMethod(get);
				outputStream = new FileOutputStream(path);
				outputStream.write(get.getResponseBody());
			}
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			get.releaseConnection();
		}
		
		return null;
	}
	/**
	 * 模拟表单登录
	 * @param loginUrl 
	 * @param data
	 */
	private static void login(String loginUrl,Map<String, String> data) {
		if(client==null) {
			client = new HttpClient();
			PostMethod post = new PostMethod(loginUrl);
			Set<Entry<String, String>> set = data.entrySet();
			for (Entry<String, String> entry : set) {
				//表单值
				post.addParameter(entry.getKey(), entry.getValue());
			}
			byte[] bytes;
			try {
				client.executeMethod(post);
				bytes = post.getResponseBody();
				String result = new String(bytes,"UTF-8");
				System.out.println("登录result:"+result);
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				post.releaseConnection();
			}
		}	
	}
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值