Java HttpCliet模擬用戶登錄並保持會話下載文件

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();
			}
		}	
	}
}

 

發佈了44 篇原創文章 · 獲贊 44 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章