安卓网络编程学习(1)——java原生网络编程(2)
写在前面
该博客紧接上篇博客:https://www.cnblogs.com/wushenjiang/p/12937531.html,继续学习post请求,带参数的post和get请求以及文件上传与下载
post请求
其实post请求的方式与get请求差不太多,我们还是先上代码:
    public void postRequest(View v) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                InputStream inputStream = null;
                try {
                    URL url = new URL(BASE_URL + "/post/comment");
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setConnectTimeout(10000);
                    httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                    httpURLConnection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
                    httpURLConnection.setRequestProperty("Accept", "application/json,text/plain,*/*");
                    CommentItem commentItem = new CommentItem("234134123", "我是评论内容...哈哈");
                    Gson gson = new Gson();
                    String jsonStr = gson.toJson(commentItem);
                    byte[] bytes = jsonStr.getBytes("UTF-8");
                    Log.d(TAG, "bytes==>" + bytes.length);
                    httpURLConnection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
                    //连接
                    httpURLConnection.connect();
                    //把数据给到服务器
                    outputStream = httpURLConnection.getOutputStream();
                    outputStream.write(bytes);
                    outputStream.flush();
                    //拿到结果
                    int responseCode = httpURLConnection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        inputStream = httpURLConnection.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        Log.d(TAG, "result ==>" + bufferedReader.readLine());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }
可以看到,与get请求不同的一点就是我们需要添加一个内容,然后把数据写入到服务端,最后关闭所有的流。整体的流程和get基本一致。
带参数的post和get请求
这里其实很类似,我们直接写一个方法统一起来:
 private void startRequest(final Map<String, String> params, final String method, final String api) {
        new Thread(new Runnable() {
            BufferedReader bufferedReader = null;
            @Override
            public void run() {
                StringBuilder sb = new StringBuilder("?");
                try {
                    //组装参数
                    if (params != null && params.size() > 0) {
                        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
                        while (iterator.hasNext()) {
                            Map.Entry<String, String> next = iterator.next();
                            sb.append(next.getKey());
                            sb.append("=");
                            sb.append(next.getValue());
                            if (iterator.hasNext()) {
                                sb.append("&");
                            }
                        }
                        Log.d(TAG, "sb result -->" + sb.toString());
                    }
                    URL url;
                    String paramsStr = sb.toString();
                    if (paramsStr != null && paramsStr.length() > 0) {
                        url = new URL(BASE_URL + api + paramsStr);
                    } else {
                        url = new URL(BASE_URL + api);
                    }
                    Log.d(TAG, "url ==>" + url.toString());
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod(method);
                    httpURLConnection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
                    httpURLConnection.setRequestProperty("Accept", "*/*");
                    httpURLConnection.connect();
                    int responseCode;
                    responseCode = httpURLConnection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        InputStream inputStream = httpURLConnection.getInputStream();
                        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        String json = bufferedReader.readLine();
                        Log.d(TAG, "result ==>" + json);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bufferedReader != null) {
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }
可以看到,我们主要就是需要将url进行一个字符串拼接,我们使用StringBuilder来进行字符串拼接,要更为安全。具体的操作流程请见代码,不用多说了。
文件上传
我们要做文件上传,其实很简单。先来上代码:
  public void postFiles(View v) {
        new Thread(new Runnable() {
            OutputStream outputStream = null;
            InputStream inputStream = null;
            @Override
            public void run() {
                try {
                    File fileOne = new File("/storage/emulated/0/Download/shop-ad.png");
                    File fileTwo = new File("/storage/emulated/0/Download/rBsADV64HDWAI6i_AAhJfxL8eXE287.png");
                    File fileThree = new File("/storage/emulated/0/Download/rBsADV64ILeAfwQMAAdBpy-0H04021.png");
                    String fileKey = "files";
                    String fileType = "image/png";
                    String BOUNDARY = "--------------------------246140106706876087289187";
//                    String BOUNDARY = "----------------------------246140106706876087289187";
                    URL url = new URL(BASE_URL + "/files/upload");
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setConnectTimeout(10000);
                    httpURLConnection.setRequestProperty("User-Agent", "Android/" + Build.VERSION.SDK_INT);
                    httpURLConnection.setRequestProperty("Accept", "*/*");
                    httpURLConnection.setRequestProperty("Cache-Control", "no-cache");
                    httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
                    httpURLConnection.setRequestProperty("Connection", "keep-alive");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);
                    //连接
                    httpURLConnection.connect();
                    outputStream = httpURLConnection.getOutputStream();
                    uploadFile(fileOne, fileKey, fileOne.getName(), fileType, BOUNDARY, outputStream, false);
                    uploadFile(fileTwo, fileKey, fileTwo.getName(), fileType, BOUNDARY, outputStream, false);
                    uploadFile(fileThree, fileKey, fileThree.getName(), fileType, BOUNDARY, outputStream, true);
                    outputStream.flush();
                    //获取返回结果
                    int responseCode = httpURLConnection.getResponseCode();
                    Log.d(TAG, "responseCode ==>" + responseCode);
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        inputStream = httpURLConnection.getInputStream();
                        BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
                        String result = bf.readLine();
                        Log.d(TAG, "result ==>" + result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //                    if (bfi != null) {
                    //                        try {
                    //                            bfi.close();
                    //                        } catch (IOException e) {
                    //                            e.printStackTrace();
                    //                        }
                    //                    }
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            private void uploadFile(File file,
                                    String fileKey,
                                    String fileName,
                                    String fileType,
                                    String BOUNDARY,
                                    OutputStream outputStream,
                                    boolean isLast) throws IOException {
                //准备数据
                StringBuilder headerSbInfo = new StringBuilder();
                headerSbInfo.append("--");
                headerSbInfo.append(BOUNDARY);
                headerSbInfo.append("\r\n");
                headerSbInfo.append("Content-Disposition: form-data; name=\"" + fileKey + "\"; filename=\"" + fileName + "\"");
                headerSbInfo.append("\r\n");
                headerSbInfo.append("Content-Type:" + fileType);
                headerSbInfo.append("\r\n");
                headerSbInfo.append("\r\n");
                byte[] headerInfoBytes = headerSbInfo.toString().getBytes("UTF-8");
                outputStream.write(headerInfoBytes);
                //文件内容
                FileInputStream fos = new FileInputStream(file);
                BufferedInputStream bfi = new BufferedInputStream(fos);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = bfi.read(buffer, 0, buffer.length)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                //写尾部信息
                StringBuilder footerSbInfo = new StringBuilder();
                footerSbInfo.append("\r\n");
                footerSbInfo.append("--");
                footerSbInfo.append(BOUNDARY);
                if (isLast) {
                    footerSbInfo.append("--");
                    footerSbInfo.append("\r\n");
                }
                footerSbInfo.append("\r\n");
                outputStream.write(footerSbInfo.toString().getBytes("UTF-8"));
            }
        }).start();
    }
仔细看,其实有点复杂。这里解释一下:
首先我们要先设置把本地的一张图设置为File类,而后设置连接的参数。之后是上传的方法 可以看到,我们上传文件的方法也是一个字符串拼接,不过拼接的是一种固定格式,我们需要按照规定的格式拼接好才能让我们的服务器识别并上传。之后将图片转换成二进制文件进行读取,之后再拼接尾部格式。之后便是返回结果了。我们通过返回结果来看看是否上传成功,之后在自己的文件夹下看看是否有文件即可。
文件下载
和上传文件相比,下载文件就没有那么复杂了,如下代码:
   public void downloadFile(View v) {
        new Thread(new Runnable() {
            FileOutputStream fileOutputStream = null;
            InputStream inputStream = null;
            @Override
            public void run() {
                try {
                    URL url = new URL(BASE_URL + "/download/10");
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setConnectTimeout(10000);
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
                    httpURLConnection.setRequestProperty("Accept", "*/*");
                    httpURLConnection.connect();
                    int responseCode = httpURLConnection.getResponseCode();
                    Log.d(TAG,"responseCode ==>"+responseCode);
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        Map<String, List<String>> headerFields = httpURLConnection.getHeaderFields();
                        for (Map.Entry<String, List<String>> stringListEntry : headerFields.entrySet()) {
                            Log.d(TAG,stringListEntry.getKey() +"==="+stringListEntry.getValue());
                        }
                        String headerField = httpURLConnection.getHeaderField("Content-disposition");
                        Log.d(TAG,"headerField -->"+headerField);
//                        int index = headerField.indexOf("filename=");
//                        String fileName = headerField.substring(index + "filename=".length());
//                        Log.d(TAG,"fileName ==>"+fileName);
                        String fileName = headerField.replace("attachment; filename=", "");
                        Log.d(TAG,"fileName ==>"+fileName);
                        File picFile = RequestTestActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                        if (!picFile.exists()) {
                            picFile.mkdirs();
                        }
                        File file = new File(picFile+fileName);
                        if(!file.exists()){
                            file.createNewFile();
                        }
                        fileOutputStream = new FileOutputStream(file);
                        inputStream = httpURLConnection.getInputStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while((len = inputStream.read(buffer,0,buffer.length)) != -1){
                            fileOutputStream.write(buffer,0,len);
                        }
                        fileOutputStream.flush();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if (inputStream != null) {
                        IOUtils.ioClose(inputStream);
                    }
                    if (fileOutputStream != null) {
                        IOUtils.ioClose(fileOutputStream);
                    }
                }
            }
        }).start();
    }
我们从服务器请求回文件,然后获取路径,新建文件和路径,然后存储进去即可。
总结
使用java API的编程操作到这里就先告一段落了,可以看到通过原生API编程的不易啊,后面我们马上学习框架使用和线程管理,就更能体会到框架的好处了。
安卓网络编程学习(1)——java原生网络编程(2)的更多相关文章
- 安卓网络编程学习(1)——java原生网络编程(1)
		
写在前面 马上要进行第二轮冲刺,考虑到自己的APP在第一轮冲刺的效果不尽人意,有很多网络方面的小BUG,这里就系统学习一下网络编程,了解来龙去脉,以便更好的对项目进行优化处理. http协议 http ...
 - 转 网络编程学习笔记一:Socket编程
		
题外话 前几天和朋友聊天,朋友问我怎么最近不写博客了,一个是因为最近在忙着公司使用的一些控件的开发,浏览器兼容性搞死人:但主要是因为这段时间一直在看html5的东西,看到web socket时觉得很有 ...
 - Java 原生网络编程.
		
一.概念 Java 语言从其诞生开始,就和网络紧密联系在一起.在 1995 年的 Sun World 大会上,当时占浏览器市场份额绝对领先的网景公司宣布在浏览器中支持Java,从而引起一系列的公司产品 ...
 - Java原生网络编程
		
一些常见术语 编程中的Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口.在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socket接口后面 ...
 - 网络编程学习笔记一:Socket编程
		
“一切皆Socket!” 话虽些许夸张,但是事实也是,现在的网络编程几乎都是用的socket. ——有感于实际编程和开源项目研究. 我们深谙信息交流的价值,那网络中进程之间如何通信,如我们每天打开浏览 ...
 - 网络编程学习笔记-全零网络IP地址0.0.0.0详谈
		
RFC: - Addresses in this block refer to source hosts on "this" network. Address may be use ...
 - JAVA学习篇--JAVA两种编程模式控制
		
在Drp项目中,解说了两种编程模式Model 1和Model2.以下是对这两种模式的简单理解.以及因为Model2是基于MVC架构的模式,就将我们易混淆的MVC与我们之前学的三层架构进行对照学习一下. ...
 - 多线程编程学习一(Java多线程的基础).
		
一.进程和线程的概念 进程:一次程序的执行称为一个进程,每个 进程有独立的代码和数据空间,进程间切换的开销比较大,一个进程包含1—n个线程.进程是资源分享的最小单位. 线程:同一类线程共享代码和数据空 ...
 - 多线程编程学习六(Java 中的阻塞队列).
		
介绍 阻塞队列(BlockingQueue)是指当队列满时,队列会阻塞插入元素的线程,直到队列不满:当队列空时,队列会阻塞获得元素的线程,直到队列变非空.阻塞队列就是生产者用来存放元素.消费者用来获取 ...
 
随机推荐
- Memcached在企业中的应用
			
Memcached简介 Memcached是一个自由开源的,高性能,分布式内存对象缓存系统. Memcached是以LiveJournal旗下Danga Interactive公司的Brad Fitz ...
 - web 之 session
			
Session? 在WEB开发中,服务器可以为每个用户浏览器创建一个会话对象(session对象),注意:一个浏览器独占一个session对象(默认情况下).因此,在需要保存用户数据时,服务器程序可以 ...
 - 学习  .net core  3----蒋金楠  笔记      构建 Asp.net core Web应用
			
前言:准备系统的学习一下.net core 所以购买了 蒋金楠的 ASP.NET CORE 3 书籍,为了加深印象 特此笔记,会持续更新到学习完为止 使用 命令行 dotnet new co ...
 - (数据科学学习手札82)基于geopandas的空间数据分析——geoplot篇(上)
			
本文示例代码和数据已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 在前面的基于geopandas的空间数据分 ...
 - centos 编码问题 编码转换 cd到对应目录 执行  中文解压
			
2019独角兽企业重金招聘Python工程师标准>>> **unzip -O CP936 xxx.zip (用GBK, GB18030也可以)** find -type f -nam ...
 - 用数据说话,R语言有哪七种可视化应用?
			
今天,随着数据量的不断增加,数据可视化成为将数字变成可用的信息的一个重要方式.R语言提供了一系列的已有函数和可调用的库,通过建立可视化的方式进行数据的呈现.在使用技术的方式实现可视化之前,我们可以先和 ...
 - Flash调用Alchemy编译的代码时出现Error #1506的解决
			
Flash调用Alchemy编译的代码时出现Error #1506的解决这个问题困扰了我很久,因为需要频繁的向Alchemy代码中传递大ByteArray数组.当某次传递的数据量较大时,后面再调用时就 ...
 - JAVA连接Excel最好用的开源项目EasyExcel,官方使用文档及.jar包下载
			
EasyExcel是一个基于Java的简单.省内存的读写Excel的开源项目.在尽可能节约内存的情况下支持读写百M的Excel. github地址:https://github.com/alibaba ...
 - 图论--割边--Tarjan模板
			
#include<iostream> #include<stdio.h> #include<vector> using namespace std; const i ...
 - MySQL高级(十三)---  表锁
			
前言:锁是计算机协调多个进程或线程并发访问某一资源的机制.在数据库中,除传统的计算机资源(如CPU.RAM.I/O等)的争用外,数据也是一种供许多用户共享的资源.如何保证数据并发访问的一致性.有效性是 ...