同样在上一篇服务器的基础上,本文客户端也在登录界面 Andriod简单http get请求基础上,用户注册后跳转到下载界面,本文下载界面只有两个View,一个是textView显示注册后用户名(本文未做登录界面,方法与注册类似,只是在服务器端查询数据库中用户名,密码是否正确)。另一个为下载按钮,点击后下载到sd卡中。
下面先将工具包,该类封装了Http请求,本文使用get方法,使用HttpURLConnection类来负责具体请求。
httpUtils类中添加sendDownloadPost方法
具体代码如下:
public static void sendDownloadPost(URL urls) { InputStream inputStream=null; //String path="http://192.168.0.179:8080/Myweb/download.do"; OutputStream outputStream=null; try { //url = new URL(urls); //本文采用HttpURLConnection,HttpClient一样可以 HttpURLConnection connection=(HttpURLConnection) urls.openConnection(); connection.setRequestMethod("GET"); //超时请求设置为3s connection.setConnectTimeout(3000); //设置响应时间10s connection.setReadTimeout(10000); connection.setDoInput(true); connection.setDoOutput(true); //获取返回码 int responseCode=connection.getResponseCode(); //请求正确 if(responseCode==200) { Log.d(TAG, "返回正确!!"); inputStream=new BufferedInputStream(connection.getInputStream()); //生成sd卡文件路径 File file=new File(Environment.getExternalStorageDirectory()+File.separator +"A.pdf"); outputStream=new BufferedOutputStream(new FileOutputStream(file)); byte[] str=new byte[2048]; int len=-1; if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { Log.d(TAG, "有权限"); //将inpustream写入到sd卡 while((len=inputStream.read(str))!=-1) { outputStream.write(str, 0, len); } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(inputStream!=null) { try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(outputStream!=null) { try { outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return; }
友情提示:本文需要添加的权限有:internet访问权限,SD卡文件读写权限,SD卡文件创建权限
具体在manifest.xml
添加如下:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
时间: 2024-11-09 18:34:12