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