首先添加依赖
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
一般下载文件都是Get请求,这里需要设置Cookie
package com.download.demo;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
public class DownUtils {
public static void main(String[] args) {
download(1, 2, 3, "param4");
}
private static void download(long param1, long param2, int param3, String param4){
String uri =String.format("http://www.xxx.com/user/statistics/association/export?start=%d&end=%d&ruleTemplateCode=sell_purchase_statistics&ruleId=%d", param1, param2, param3);
HttpConnectionManager manager = new SimpleHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
params.setConnectionTimeout(5000);
params.setSoTimeout(5000);
manager.setParams(params);
HttpClient client = new HttpClient(manager);
GetMethod method = new GetMethod(uri);
method.addRequestHeader("Cookie", "token=MzsyOzgyNDUyOzEwMDAwNzoxNjUzMzU3MzQ5NjI2OmM3ZWQ5ZDk0Y2I4YmFkNjMyYWY4MDZlZGM1YzYzZTlh;");
try{
client.executeMethod(method);
int statusCode = method.getStatusCode();
if (statusCode == 200) {
InputStream in = method.getResponseBodyAsStream();
File file = new File("D:/temp2/" + param1+ "-" + param2 + "-" +param3);
FileOutputStream fout = new FileOutputStream(file);
int a = -1;
byte[] tmp = new byte[1024];
while ((a = in.read(tmp)) != -1) {
fout.write(tmp, 0, a);
}
fout.flush();
fout.close();
in.close();
}
}catch (Exception e){
e.printStackTrace();
}finally {
method.releaseConnection();
}
}
}
|