应用场景:
手机端使用apache的httpclient组件。
服务器端使用spring+cxf rest webservice
手机端代码:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
public class HttpClientTest {
private final static String REMOTE_FILE_URL = "http://localhost:8080/cxf_restful_webservice/rws/pdf/get";
private final static int BUFFER = 1024;
public static void main(String[] args) {
HttpClient client = new HttpClient();
PostMethod httpGet = new PostMethod(REMOTE_FILE_URL);
try {
client.executeMethod(httpGet);
InputStream in = httpGet.getResponseBodyAsStream();
Header[] h = httpGet.getResponseHeaders("Content-Disposition");
// NameValuePair ss = httpGet.getParameter("Content-Disposition");
// String name = ss.getName();
// String value = ss.getValue();
String dispositionValue = h[0].getValue();
int index = dispositionValue.indexOf("=");
String fileName = dispositionValue.substring(index+1);
System.out.println(h[0]);
System.out.println(fileName);
FileOutputStream out = new FileOutputStream(new File("D:\\upload\\"+fileName));
byte[] b = new byte[BUFFER];
int len = 0;
while((len=in.read(b))!= -1){
out.write(b,0,len);
}
in.close();
out.close();
}catch (HttpException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
httpGet.releaseConnection();
}
System.out.println("download, success!!");
}
}
服务端代码:
import java.io.File;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
@Path("/zip")
public class PdfService {
private static final String FILE_PATH = "c:\\xxx.zip";
@POST
@Path("/get")
@Produces("application/pdf")
public Response getFile() {
File file = new File(FILE_PATH);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename=xxx.zip");
return response.build();
}
}