服务端提供了一个servlet,例如:http://127.0.62.12:4456/download.do.例如在服务器有个包在目录e:/test/tb.zip。 客户端如果如何用httpclient去调用servlet去到服务器的一个目录下下载这个个zip包?servlet该如何写?如果这个zip包很大该怎么实现?能给个实例最好了。
------解决思路----------------------
servlet 如下
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DownloadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = "下载.zip";
String rname = new String(filename.getBytes("utf-8"),"iso-8859-1");
response.addHeader("Content-Disposition", "attachment;filename="+rname);
response.setContentType("application/octet-stream");
File file = new File("e://test//tb.zip");
InputStream is = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[is.available()];
is.read(buffer);
is.close();
OutputStream os = new BufferedOutputStream(response.getOutputStream());
os.write(buffer);
os.flush();
os.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
------解决思路----------------------
httpclient接收如下
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class ClientA {
public void service(){
String url = "http://192.168.1.121:7503/download/DownloadServlet";
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get);
InputStream is = response.getEntity().getContent();
String localfile = "D://aaa.zip";
File file = new File(localfile);
if(!file.exists()){
file.createNewFile();
}
OutputStream os = new FileOutputStream(file);
int read = 0;
byte[] temp = new byte[1024*1024];
while((read=is.read(temp))>0){
byte[] bytes = new byte[read];
System.arraycopy(temp, 0, bytes, 0, read);
os.write(bytes);
}
os.flush();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ClientA client = new ClientA();
client.service();
}
}
------解决思路----------------------
byte[] buffer = new byte[is.available()];
is.read(buffer);
这里会不会有问题,文件大的时候读取不玩数据