androidhttp下载文件|android通过http post实现文件下载

① android从tomcat下载文件

从tomcat下载文件的配置有几种,以下是常用的设置方式:

创建虚拟目录

首先停止Tomcat服务。打开tomcat里找到conf这个文件夹下的server.xml文件,在里面找到</Host> 在上面 加上这样的一段:

<Context path="" docBase="d:/download" crossContext="false" debug="0" reloadable="true"></Context>

然后把tomcat启动一下就OK

在tomcat首页中显示根目录下的文件列表

是否显示文件列表,可以在tomcat/conf/web.xml里配置,把 <init-param>

<param-name>listings</param-name> <param-value>false</param-value> </init-param>里的<param-value>false</param-value>改成<param-value>ture</param-value>即可显示。 默认的是false 。

增加新的文件类型

打开tomcat/conf/web.xml文件,添加.cfg和.Ini的文件类型。 <mime-mapping>

<extension>cfg</extension>

<mime-type>application/octet-stream</mime-type>

</mime-mapping> <mime-mapping>

<extension>ini</extension>

<mime-type>application/octet-stream</mime-type>

</mime-mapping>

以上内容都设置好后,重新启动tomcat服务 进入测试。

打开IE,在地址栏中输入http://localhost:你的tomcat端口,在IE中列出虚拟目录d:download下的文件列表,双击某个文件或右键选择“目标另存为”就可以下载文件了。

② android如何调用系统自带文件下载功能

文件下载是那种从网上下载的那种吗?如果是的话有一种http下载1.直接打开文件A.创建一个一个URL对象url = new URL(urlStr);这个url可以直接是网络下载地址。B.通过URL对象,创建一个HttpURLConnection对象// 创建一个Http连接HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();C.得到InputStram,这个输入流相当于一个管道,将网络上的数据引导到手机上。但是单纯的对于InputStram不好进行操作,它是字节流,因此用InputStreamReader把它转化成字符流。然后在它上面再套一层BufferedReader,这样就能整行的读取数据,十分方便。这个在java的socket编程中我们已经见识过了。// 使用IO流读取数据buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));D.从InputStream当中读取数据while ((line = buffer.readLine()) != null) {sb.append(line);}2.文件存到sd卡中SDPATH = Environment.getExternalStorageDirectory() + "/" File dir = new File(SDPATH + dirName);dir.mkdirs();File file = new File(SDPATH + dirName + fileName);file.createNewFile()url = new URL(urlStr);这个url可以直接是网络下载地址。HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();inputStream inputStream =urlConn.getInputStream()output = new FileOutputStream(file);byte buffer [] = new byte[4 * 1024];while((inputStream.read(buffer)) != -1){output.write(buffer);}//

③ android 如何从tomcat服务器上下载文件

//下载private InputStream FileDownload(String url_str) throws Exception{URL url = new URL(url_str);// 创建连接HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(3000);conn.setConnectTimeout(3000);conn.connect();// 获取文件大小length = conn.getContentLength();// 创建输入流InputStream is = conn.getInputStream();return is;}//保存private void FileSave(String filename,InputStream is,int length) throws Exception{File file = new File(mSavePath);// 判断文件目录是否存在if (!file.exists()){file.mkdir();}File apkFile = new File(mSavePath, filename);FileOutputStream fos = new FileOutputStream(apkFile);int count = 0;// 缓存byte buf[] = new byte[1024];// 写入到文件中do{int numread = is.read(buf);count += numread;// 计算进度条位置progress = (int) (((float) count / length) * 100);// 更新进度mHandler.sendEmptyMessage(DOWNLOAD);if (numread <= 0){// 下载完成mHandler.sendEmptyMessage(DOWNLOAD_FINISH);break;}// 写入文件fos.write(buf, 0, numread);} while (!cancelUpdate);// 点击取消就停止下载.fos.close();}/*** 安装APK文件*/private void installApk(){File apkfile = new File(mSavePath, mHashMap.get("name"));if (!apkfile.exists()){return;}// 通过Intent安装APK文件Intent i = new Intent(Intent.ACTION_VIEW);i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");mContext.startActivity(i);}

④ android原生开发,从http下载图片,下载失败或成功提示,并放图片显示出来。

下载类public class DownFile { public InputStream getInput(String path) { InputStream in = null; try { URL url = new URL(path); HttpURLConnection hcon = (HttpURLConnection) url.openConnection(); in = hcon.getInputStream(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return in; } public int downIamge(String path,String name) { InputStream in = getInput(path); int type = 0; File ex = Environment.getExternalStorageDirectory(); try { FileOutputStream out = new FileOutputStream(new File(ex.getAbsoluteFile()+File.separator+name)); int len = 0; byte[] bb = new byte[1024]; while((len = in.read(bb))!=-1) { out.write(bb,0,len); } out.close(); type = 1; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); type = 2; } return type; }}2在另外一个activity里面调用这个方法DownFile().downIamge(path,name); 返回1就是下载成功 ,2 就显示下载失败自己手写的 望采纳 不懂 可继续追问

⑤ android 如何实现一次http请求下载过个文件如:请求http://192.168.1.2:8088/a.jsp,获得a.jpg,b.jpg

如果在服务器端向response里面写入多个文件的数据当然可以下载,只不过需要服务器端和手机端的程序制定一个协议,比如手机端得到数据之后根据什么规则切分成多个文件。

⑥ 怎么用http协议实现安卓数据

网上介绍Android上http通信的文章很多,不过大部分只给出了实现代码的片段,一些注意事项和如何设计一个合理的类用来处理所有的http请求以及返回结果,一般都不会提及。因此,自己对此做了些总结,给出了我的一个解决方案。首先,需要明确一下http通信流程,Android目前提供两种http通信方式,HttpURLConnection和HttpClient,HttpURLConnection多用于发送或接收流式数据,因此比较适合上传/下载文件,HttpClient相对来讲更大更全能,但是速度相对也要慢一点。在此只介绍HttpClient的通信流程:1.创建HttpClient对象,改对象可以用来多次发送不同的http请求2.创建HttpPost或HttpGet对象,设置参数,每发送一次http请求,都需要这样一个对象3.利用HttpClient的execute方法发送请求并等待结果,该方法会一直阻塞当前线程,直到返回结果或抛出异常。4.针对结果和异常做相应处理根据上述流程,发现在设计类的时候,有几点需要考虑到:1.HttpClient对象可以重复使用,因此可以作为类的静态变量2.HttpPost/HttpGet对象一般无法重复使用(如果你每次请求的参数都差不多,也可以重复使用),因此可以创建一个方法用来初始化,同时设置一些需要上传到服务器的资源3.目前Android不再支持在UI线程中发起Http请求,实际上也不该这么做,因为这样会阻塞UI线程。因此还需要一个子线程,用来发起Http请求,即执行execute方法4.不同的请求对应不同的返回结果,对于如何处理返回结果(一般来说都是解析json&更新UI),需要有一定的自由度。5.最简单的方法是,每次需要发送http请求时,开一个子线程用于发送请求,子线程中接收到结果或抛出异常时,根据情况给UI线程发送message,最后在UI线程的handler的handleMessage方法中做结果解析和UI更新。这么写虽然简单,但是UI线程和Http请求的耦合度很高,而且代码比较散乱、丑陋。基于上述几点原因,我设计了一个PostRequest类,用于满足我的http通信需求。我只用到了Post请求,如果你需要Get请求,也可以改写成GetRequestpackage com.handspeaker.network;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URI;import java.net.URISyntaxException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.HttpConnectionParams;import org.apache.http.params.HttpParams;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import org.json.JSONObject;import android.app.Activity;import android.content.Context;import android.net.ConnectivityManager;import android.os.Handler;import android.util.Log;/** * * 用于封装&简化http通信 * */public class PostRequest implements Runnable { private static final int NO_SERVER_ERROR=1000; //服务器地址 public static final String URL = "fill your own url"; //一些请求类型 public final static String ADD = "/add"; public final static String UPDATE = "/update"; public final static String PING = "/ping"; //一些参数 private static int connectionTimeout = 60000; private static int socketTimeout = 60000; //类静态变量 private static HttpClient httpClient=new DefaultHttpClient(); private static ExecutorService executorService=Executors.newCachedThreadPool(); private static Handler handler = new Handler(); //变量 private String strResult; private HttpPost httpPost; private HttpResponse httpResponse; private OnReceiveDataListener onReceiveDataListener; private int statusCode; /** * 构造函数,初始化一些可以重复使用的变量 */ public PostRequest() { strResult = null; httpResponse = null; httpPost = new HttpPost(); } /** * 注册接收数据监听器 * @param listener */ public void setOnReceiveDataListener(OnReceiveDataListener listener) { onReceiveDataListener = listener; } /** * 根据不同的请求类型来初始化httppost * * @param requestType * 请求类型 * @param nameValuePairs * 需要传递的参数 */ public void iniRequest(String requestType, JSONObject jsonObject) { httpPost.addHeader("Content-Type", "text/json"); httpPost.addHeader("charset", "UTF-8"); httpPost.addHeader("Cache-Control", "no-cache"); HttpParams httpParameters = httpPost.getParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout); HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout); httpPost.setParams(httpParameters); try { httpPost.setURI(new URI(URL + requestType)); httpPost.setEntity(new StringEntity(jsonObject.toString(), HTTP.UTF_8)); } catch (URISyntaxException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** * 新开一个线程发送http请求 */ public void execute() { executorService.execute(this); } /** * 检测网络状况 * * @return true is available else false */ public static boolean checkNetState(Activity activity) { ConnectivityManager connManager = (ConnectivityManager) activity .getSystemService(Context.CONNECTIVITY_SERVICE); if (connManager.getActiveNetworkInfo() != null) { return connManager.getActiveNetworkInfo().isAvailable(); } return false; } /** * 发送http请求的具体执行代码 */ @Override public void run() { httpResponse = null; try { httpResponse = httpClient.execute(httpPost); strResult = EntityUtils.toString(httpResponse.getEntity()); } catch (ClientProtocolException e1) { strResult = null; e1.printStackTrace(); } catch (IOException e1) { strResult = null; e1.printStackTrace(); } finally { if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { statusCode=NO_SERVER_ERROR; } if(onReceiveDataListener!=null) { //将注册的监听器的onReceiveData方法加入到消息队列中去执行 handler.post(new Runnable() { @Override public void run() { onReceiveDataListener.onReceiveData(strResult, statusCode); } }); } } } /** * 用于接收并处理http请求结果的监听器 * */ public interface OnReceiveDataListener { /** * the callback function for receiving the result data * from post request, and further processing will be done here * @param strResult the result in string style. * @param StatusCode the status of the post */ public abstract void onReceiveData(String strResult,int StatusCode); }}代码使用了观察者模式,任何需要接收http请求结果的类,都要实现OnReceiveDataListener接口的抽象方法,同时PostRequest实例调用setOnReceiveDataListener方法,注册该监听器。完整调用步骤如下:1.创建PostRequest对象,实现onReceiveData接口,编写自己的onReceiveData方法2.注册监听器3.调用PostRequest的iniRequest方法,初始化本次request4.调用PostRequest的execute方法可能的改进:1.如果需要多个观察者,可以把只能注册单个监听器改为可以注册多个监听器,维护一个监听器List。2.如果需求比较简单,并希望调用流程更简洁,iniRequest和execute可以合并

⑦ 发送HTTP请求并下载文件怎么做

无论手机还是电脑都要!不下载怎么看?你话没说明白,我没听懂,不过就我用手机或电子信箱,看收到的文件都要下载来看的,你问的是有关手机的问题,那我告诉你手机收到图片还有文件都是要下载的,就算是看视频也要网络浏览器,比如uc视频之类的,除非是网盘上下来的,不要流量!还有问题也可以继续问我

⑧ 安卓如何实现输入url通过url将网络资源下载并储存到本地(无论什么文件类型都可以下载)

你可以搜一下xUtils框架,里面有个HttpUtils模块就是专门实现这个功能的

⑨ Android中从Http上下载一个Zip文件,解压缩 到SDCard

你上网搜索解析zip文件的代码 将服务器的zip文件以流的形式读取过来直接解析放到sd卡就行

⑩ android通过http post实现文件下载

可参照我的如下代码

java.io.OutputStreamos=null;java.io.InputStreamis=null;try{java.io.Filefile=newjava.io.File(str_local_file_path);if(file.exists()&&file.length()>0){}else{file.createNewFile();java.net.URLurl=newjava.net.URL(str_url);java.net.HttpURLConnectionconn=(java.net.HttpURLConnection)url.openConnection();os=newjava.io.FileOutputStream(file);is=conn.getInputStream();byte[]buffer=newbyte[1024*4];intn_rx=0;while((n_rx=is.read(buffer))>0){os.write(buffer,0,n_rx);}}returntrue;}catch(MalformedURLExceptione){}catch(IOExceptione){}finally{os.flush();os.close();is.close();}returnfalse;


赞 (0)