} } }

    servlet httpClient 长途文件

    添加时间:2013-5-10 点击量:

    经由过程webService调用长途办事,返回了一个文件地址,如今须要从这个地址,我采取了servlet来实现。在网上发了然一个斗劲好的办法,如今和大师分享一下,若是有不完美的处所,还请多多指教。


    须要用到的org.apache.commons.httpclient.jar 已上传。


    一下就是我的代码:



     1 import java.io.File;
    
    2 import java.io.FileOutputStream;
    3 import java.io.IOException;
    4
    5 import javax.servlet.ServletException;
    6 import javax.servlet.http.HttpServlet;
    7 import javax.servlet.http.HttpServletRequest;
    8 import javax.servlet.http.HttpServletResponse;
    9
    10 import org.apache.commons.httpclient.HttpClient;
    11 import org.apache.commons.httpclient.methods.GetMethod;
    12
    13 public class GetAllPolicyServlet extends HttpServlet {
    14
    15 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    16 doPost(request, response);
    17 }
    18
    19 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    20 HttpClient client = new HttpClient();
    21 GetMethod get = null;
    22 try {
    23 //须要导入 org.apache.commons.httpclient.jar包 该文件须要别的
    24 String path = http://58.83.209.199:91/download/yeexing/201305090954476272020.zip;
    25 get = new GetMethod(path);
    26 int i = client.executeMethod(get);
    27 if (200 == i) {
    28 File storeFile = new File(d:/201305090954476272020.zip);
    29 FileOutputStream output = new FileOutputStream(storeFile);
    30 output.write(get.getResponseBody());
    31 output.close();
    32 } else {
    33 System.out.println(no pic);
    34 }
    35 } catch (Exception e) {
    36 System.out.println(no pic);
    37 } finally {
    38 get.releaseConnection();
    39 client.getHttpConnectionManager().closeIdleConnections(0);
    40 }
    41 }
    42
    43 }


    无论对感情还是对生活,“只要甜不要苦”都是任性而孩子气的,因为我们也不完美,我们也会伤害人。正因为我们都不完美,也因为生活从不是事事如意,所以对这些“瑕疵”的收纳才让我们对生活、对他人的爱变得日益真实而具体。—— 汪冰《世界再亏欠你,也要敢于拥抱幸福》
    分享到: