网络请求总结

1.get请求

/**
     * Host 要访问的主机
     * Connection 连接保持,http1.1有,1.0没有这个。keep-alive可以提高效率,在一定时间里不断开tcp连接,进行下一个请求
     * Content-Length 内容长度,指的是后面请求正文的数据长度
     * Accept 响应内容格式,也就是返回内容格式
     * Origin 这个是源(不是标准http里的内容,因为我访问用的是chrome,是chrome加的)
     * User-Agent 用户客户端相关的信息,比如说浏览器呀,操作系统信息之类的
     * Content-Type 提交的内容类型,我提及的是json,编码是utf-8
     * Referer 来源,访问入口,比如说你在搜索引擎百度里搜索阳光沙滩,进入到网站,那么这个来源就是百度了
     * Accept-Encoding 响应内容的编码格式
     * Accept-Language 响应内容的语言
     * Cookie cookies
     */
    private void loadNetwork() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // URL url = new URL("http://192.168.0.107:9102/get/text");
                    URL url = new URL("http://192.168.0.100:9102/get/text");
                    // URL url = new URL("http://192.168.230.222:9102/get/text");
                    // URL url = new URL("https://api.sunofbeaches.com/shop/api/discovery/categories");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(10000); // 设置超时时间
                    connection.setRequestMethod("GET"); // 设置请求方式为 “GET”
                    connection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9"); // 设置支持的语言
                    connection.setRequestProperty("Accept","*/*"); // 设置响应内容格式
                    // connection.setRequestProperty("connection", "Keep-Alive");
                    // connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
                    connection.connect();
                    // 结果码
                    int responseCode = connection.getResponseCode();
                    Log.d(TAG, " cfx responseCode = " + responseCode);
                    if (responseCode == 200) {
                        Map<String, List<String>> headerFields = connection.getHeaderFields();
                        Set<Map.Entry<String, List<String>>> entries = headerFields.entrySet();
                        for (Map.Entry<String, List<String>> entry : entries) {
                            String key = entry.getKey();
                            List<String> value = entry.getValue();
                            for (String s : value) {
                                Log.d(TAG, " cfx key = " + key + " --> " + s);
                            }
                        }
                        // 拿到内容
                        Object content = connection.getContent();
                        Log.d(TAG, " cfx content = " + content);
                        InputStream inputStream = connection.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        // Log.d(TAG, " cfx bufferedReader.readLine() = " + bufferedReader.readLine());
                        String json = bufferedReader.readLine();
                        Gson gson = new Gson();
                        GetTextItem getTextItem = gson.fromJson(json, GetTextItem.class);
                        // 更新UI
                        updateUi(getTextItem);

                    }
                } catch (Exception e) {
                    Log.d(TAG, " loadNetwork Exception = " + e);
                }
            }
        }).start();
    }

请求过程:

1、建立拿到URL

2、通过URL建立HttpURLConnection连接,设置请求头信息,通过connection方法进行连接

3、建立连接后,通过connection.getResponseCode()拿到请求码,判断当前请求连接状态,请求码为HttpURLConnection.HTTP_OK(200)表示成功连接

4、连接成功后,通过connection.getContent()拿到请求的内容

5、通过connection.getInputStream()获取输入流

6、通过Gson将读取的内容转换实体bean类(通过gson.fromJson方法)

7、以上操作在子线程完成,拿到实体bean类后,在主线程设置数据,更新UI即可

2.通过网络请求加载大图

/**
     * 加载图片,异步线程操作
     */
    private void loadPic() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(
                                "https://t7.baidu.com/it/u=1087431467,413818649&fm=167&fmt=auto&app=43&f=JPEG?w=500&h=500&s=612AB1556A8B52DC5B3D318F0300C0E2");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(10000);
                    connection.setRequestMethod("GET"); // 设置请求方式为 “GET”
                    connection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9"); // 设置支持的语言
                    connection.setRequestProperty("Accept","*/*"); // 设置响应内容格式
                    connection.connect();
                    // 结果码
                    int responseCode = connection.getResponseCode();
                    Log.d(TAG, " cfx responseCode = " + responseCode);
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        InputStream inputStream = connection.getInputStream();
                        final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        // 更新UI在主线程
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ImageView pic = findViewById(R.id.pic_iv);
                                pic.setImageBitmap(bitmap);
                            }
                        });
                    }
                } catch (Exception e) {
                    Log.d(TAG, " loadPic Exception = " + e);
                }
            }
        }).start();
    }
/**
     * 加载大图片
     * 进行降采样处理
     */
    private void loadBigPic() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                BitmapFactory.Options options = new BitmapFactory.Options();
                final ImageView pic = findViewById(R.id.pic_iv);
                // 1.根据控件的大小,动态的进行计算降采样的值
                options.inJustDecodeBounds = true; // 设置为true会拿到图片的大小,但不会加载到内存
                BitmapFactory.decodeResource(getResources(), R.mipmap.bigpicture, options);
                // 2.获取当前图片的宽高(获取的是原图片的分辨率)
                int outWidth = options.outWidth;
                int outHeight = options.outHeight;
                Log.d(TAG, "cfx outHeight = " + outHeight + " outWidth = " + outWidth);
                // 3.拿到控件的尺寸(获取的是px)
                int measuredHeight = pic.getMeasuredHeight();
                int measuredWidth = pic.getMeasuredWidth();
                Log.d(TAG, "cfx measuredHeight = " + measuredHeight + " measuredWidth = " + measuredWidth);
                options.inSampleSize = 1; // 默认等于1时表示原比例,没有进行降采样
                // 图片的宽度/控件的宽度
                // 图片的高度/控件的高度
                int maxHeight = outHeight / measuredHeight;
                int maxWidth = outWidth / measuredWidth;
                options.inSampleSize = Math.max(maxHeight, maxWidth);
                Log.d(TAG, "cfx options.inSampleSize = " + options.inSampleSize);
                options.inJustDecodeBounds = false; // 置为false,否则返回空对象
                final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bigpicture, options);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pic.setImageBitmap(bitmap);
                    }
                });
            }
        }).start();
    }
/**
     * 计算降采样率的算法
     * @param options
     * @param maxWidth
     * @param maxHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int maxWidth, int maxHeight) {
        //这里其实是获取到默认的高度和宽度,也就是图片的实际高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        //默认采样率为1,也就是不变嘛。
        int inSampleSize = 1;

        //===============核心算法啦====================
        if (width > maxWidth || height > maxHeight) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) maxHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) maxWidth);
            }
            final float totalPixels = width * height;
            final float maxTotalPixels = maxWidth * maxHeight * 2;
            while (totalPixels / (inSampleSize * inSampleSize) > maxTotalPixels) {
                inSampleSize++;
            }
        }
        //=============核心算法end================
        return inSampleSize;
    }

请求方法同上面类似,步骤

1、拿到输入流后,通过BitmapFactory.decodeStream(inputStream)转换成Bitmap对象

2、在主线程设置更新UI

3、对于大图,先要进行降采样处理,防止OOM

3、post不带参数请求过程

private void postRequest() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedReader bufferedReader = null;
                try {
                    URL url = new URL(BASE_URL + "post/comment");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(10000); // 设置超时时间
                    connection.setRequestMethod("POST"); // 设置请求方式为 “POST”
                    connection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
                    connection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9"); // 设置支持的语言
                    connection.setRequestProperty("Accept", "application/json, text/plain, */*"); // 设置响应内容格式
                    CommentItem commentItem = new CommentItem("12344321", "这是Post提交的评论内容");
                    Gson gson = new Gson();
                    String jsonStr = gson.toJson(commentItem);
                    byte[] bytes = jsonStr.getBytes("UTF-8");
                    // 设置长度
                    connection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
                    // 进行连接
                    connection.connect();
                    // 把数据发送给服务端
                    outputStream = connection.getOutputStream();

                    outputStream.write(bytes);
                    outputStream.flush();
                    // 写完之后,拿返回的结果
                    int responseCode = connection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        InputStream inputStream = connection.getInputStream();
                        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        Log.d(TAG, " cfx bufferedReader.readLine() = " + bufferedReader.readLine());
                    }
                } catch (Exception e) {
                    Log.d(TAG, "Exception = " + e);
                } finally {
                    if (bufferedReader != null) {
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            Log.d(TAG, " IOException = " + e);
                        }
                    }
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            Log.d(TAG, " IOException = " + e);
                        }
                    }
                }
            }
        }).start();
    }

步骤:

1、通过URL设置参数信息

2、构建要传输的内容(创建bean对象),通过gson.toJson转换为json对象,并转换为byte数组

3、进行连接,获取数据数据流,将构建的内容写出去

4、拿到返回的结果,通过输入流获取

5、最后关流即可

4、post带参数请求的过程

private void startRequest(Map<String, String> params, String method, String api) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    StringBuffer sb = new StringBuffer();
                    sb.append("?");
                    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, "cfx sb.toString() = " + sb.toString());
                    String urlStr = BASE_URL + api + sb.toString();
                    Log.d(TAG, "cfx urlStr = " +urlStr);
                    URL url = new URL(urlStr);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(10000); // 设置超时时间
                    connection.setRequestMethod(method); // 设置请求方式为
                    connection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9"); // 设置支持的语言
                    connection.setRequestProperty("Accept","*/*"); // 设置响应内容格式
                    connection.connect();
                    // 结果码
                    int responseCode = connection.getResponseCode();
                    Log.d(TAG, " cfx responseCode = " + responseCode);
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        Log.d(TAG, "cfx 返回成功");
                        // 拿到内容
                        Object content = connection.getContent();
                        Log.d(TAG, " cfx content = " + content);
                        InputStream inputStream = connection.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        String json = bufferedReader.readLine();
                        Log.d(TAG, "cfx json = " + json);
                    }
                } catch (Exception e) {
                    Log.d(TAG, " cfx Exception = " + e);
                }
            }
        }).start();
    }

总结:先通过sb拼接要提交的参数内容即可

5、post上传单个文件过程

/**
     * 上传单个文件
     */
    private void postFile() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedInputStream bufferedInputStream = null;
                BufferedReader bufferedReader = null;
                try {
                    File file = new File("/storage/self/primary/DCIM/Camera/20200130_101215.jpg");
                    if(!file.exists())
                    {
                        file.createNewFile();
                        Log.d(TAG, "cfx=======");
                    }
                    String fileKey = "file";
                    String fileName = file.getName();
                    String fileType = "image/jpeg";
                    String boundary = "----WebKitFormBoundaryShrHmUhavaCdnltz";
                    URL url = new URL(BASE_URL + "file/upload");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(10000); // 设置超时时间
                    connection.setRequestMethod("POST"); // 设置请求方式为 “POST”
                    connection.setRequestProperty("User-Agent", "Android/" + Build.VERSION.SDK_INT);
                    connection.setRequestProperty("Accept", "*/*");
                    connection.setRequestProperty("Cache-Control", "no-cache");
                    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
                    connection.setRequestProperty("Connection","keep-alive");
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    // 1.连接
                    connection.connect();
                    outputStream = connection.getOutputStream();
                    // 2.准备数据
                    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");
                    Log.d(TAG, "cfx headerSbInfo.toString() = " + headerSbInfo.toString());
                    byte[] headerInfoBytes = headerSbInfo.toString().getBytes("UTF-8");
                    outputStream.write(headerInfoBytes);
                    /**
                     * 3.文件内容
                     * 注意有时文件上传不成功
                     * 可能是因为图片文件的内存太大了
                     */
                    FileInputStream fileInputStream = new FileInputStream(file);
                    bufferedInputStream = new BufferedInputStream(fileInputStream);
                    byte[] bytes = new byte[1024];
                    int len;
                    while ((len = bufferedInputStream.read(bytes)) != -1) {
                        Log.d(TAG, "cfx len = " + len);
                        outputStream.write(bytes, 0, len);
                    }
                    // 4.写尾部信息
                    StringBuilder footerSbInfo = new StringBuilder();
                    footerSbInfo.append("\r\n");
                    footerSbInfo.append("--");
                    footerSbInfo.append(boundary);
                    footerSbInfo.append("--");
                    footerSbInfo.append("\r\n");
                    footerSbInfo.append("\r\n");
                    Log.d(TAG, "cfx footerSbInfo.toString() = " + footerSbInfo.toString());
                    byte[] footerSbBytes = footerSbInfo.toString().getBytes("UTF-8");
                    outputStream.write(footerSbBytes);
                    outputStream.flush();
                    // 获取返回结果
                    int responseCode = connection.getResponseCode();
                    Log.d(TAG, "cfx responseCode = " + responseCode);
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        Log.d(TAG, "cfx POST上传文件成功");
                        InputStream inputStream = connection.getInputStream();
                        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        Log.d(TAG, "cfx " + bufferedReader.readLine());
                    }

                } catch (Exception e) {
                    Log.d(TAG, " postFile Exception = " + e);
                } finally {
                    if (bufferedReader != null) {
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            Log.d(TAG, "postFile bufferedReader IOException " + e);
                        }
                    }
                    if (bufferedInputStream != null) {
                        try {
                            bufferedInputStream.close();
                        } catch (IOException e) {
                            Log.d(TAG, "postFile bufferedInputStream IOException " + e);
                        }
                    }
                    if (outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            Log.d(TAG, "postFile outputStream IOException " + e);
                        }
                    }
                }
            }
        }).start();
    }

步骤1:通过文件所在的路径创建File

2、建立起Url,并设置相应的参数进行连接

3、先准备上传文件的头部信息字符串,并转为字节数组,通过输出流写出去

4、准备文件输入流,读取文件,边读变通过输出流写出去

5、写尾部信息,写完通过连接的输入流获取返回的结果

6、最后关流即可

6、post上传多个文件

// 上传多个文件
    private void postFileMore() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedInputStream bufferedInputStream = null;
                BufferedReader bufferedReader = null;
                try {
                    File file = new File("/storage/self/primary/DCIM/Camera/20200130_101215.jpg");
                    File file2 = new File("/storage/self/primary/DCIM/Camera/20201030_153627.jpg");
                    File file3 = new File("/storage/self/primary/DCIM/Camera/20210214_204403.jpg");
                    if(!file.exists()) {
                        file.createNewFile();
                        Log.d(TAG, "cfx=======");
                    }
                    if(!file2.exists()) {
                        file2.createNewFile();
                        Log.d(TAG, "cfx=======");
                    }
                    if(!file3.exists()) {
                        file3.createNewFile();
                        Log.d(TAG, "cfx=======");
                    }
                    String fileKey = "files";
                    String fileName = file.getName();
                    String fileName2 = file2.getName();
                    String fileName3 = file3.getName();
                    String fileType = "image/jpeg";
                    String boundary = "----WebKitFormBoundaryShrHmUhavaCdnltz";
                    URL url = new URL(BASE_URL + "files/upload");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(10000); // 设置超时时间
                    connection.setRequestMethod("POST"); // 设置请求方式为 “POST”
                    connection.setRequestProperty("User-Agent", "Android/" + Build.VERSION.SDK_INT);
                    connection.setRequestProperty("Accept", "*/*");
                    connection.setRequestProperty("Cache-Control", "no-cache");
                    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
                    connection.setRequestProperty("Connection","keep-alive");
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    // 1.连接
                    connection.connect();
                    outputStream = connection.getOutputStream();
                    // 2.准备数据
                    uploadFiles(outputStream, bufferedInputStream, file, fileKey, fileName, fileType, boundary,
                            false); // 文件1
                    uploadFiles(outputStream, bufferedInputStream, file2, fileKey, fileName2, fileType, boundary,
                            false); // 文件2
                    uploadFiles(outputStream, bufferedInputStream, file3, fileKey, fileName3, fileType, boundary,
                            true); // 文件3(最后一个文件)
                    outputStream.flush();
                    // 获取返回结果
                    int responseCode = connection.getResponseCode();
                    Log.d(TAG, "cfx responseCode = " + responseCode);
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        Log.d(TAG, "cfx POST上传多个文件成功");
                        InputStream inputStream = connection.getInputStream();
                        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        Log.d(TAG, "cfx " + bufferedReader.readLine());
                    }

                } catch (Exception e) {
                    Log.d(TAG, " postFile Exception = " + e);
                } finally {
                    CloseIo.CloseIoStream(bufferedReader);
                    CloseIo.CloseIoStream(bufferedInputStream);
                    CloseIo.CloseIoStream(outputStream);
                }
            }
        }).start();
    }

    // 上传文件
    private void uploadFiles(OutputStream outputStream, BufferedInputStream bufferedInputStream, File file,
                             String fileKey, String fileName, String fileType,
                             String boundary, boolean isLastFile) 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");
        Log.d(TAG, "cfx headerSbInfo.toString() = " + headerSbInfo.toString());
        byte[] headerInfoBytes = headerSbInfo.toString().getBytes("UTF-8");
        outputStream.write(headerInfoBytes);
        /**
         * 3.文件内容
         * 注意有时文件上传不成功
         * 可能是因为图片文件的内存太大了
         */
        FileInputStream fileInputStream = new FileInputStream(file);
        bufferedInputStream = new BufferedInputStream(fileInputStream);
        byte[] bytes = new byte[1024];
        int len;
        while ((len = bufferedInputStream.read(bytes)) != -1) {
            Log.d(TAG, "cfx len = " + len);
            outputStream.write(bytes, 0, len);
        }
        // 4.写尾部信息
        StringBuilder footerSbInfo = new StringBuilder();
        footerSbInfo.append("\r\n");
        if (isLastFile) { // 是否是最后一个文件
            footerSbInfo.append("--");
            footerSbInfo.append(boundary);
            footerSbInfo.append("--");
            footerSbInfo.append("\r\n");
            footerSbInfo.append("\r\n");
        }
        Log.d(TAG, "cfx footerSbInfo.toString() = " + footerSbInfo.toString());
        byte[] footerSbBytes = footerSbInfo.toString().getBytes("UTF-8");
        outputStream.write(footerSbBytes);
    }

7、get下载文件过程

// 下载文件
    private void downloadFile() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileOutputStream fileOutputStream = null;
                BufferedInputStream bufferedInputStream = null;
                InputStream inputStream = null;
                try {
                    URL url = new URL(BASE_URL + "download/5");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(10000); // 设置超时时间
                    connection.setRequestMethod("GET"); // 设置请求方式为 “GET”
                    connection.setRequestProperty("Accept", "*/*");
                    connection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9"); // 设置支持的语言
                    connection.connect();
                    int responseCode = connection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        // Map<String, List<String>> headerFields = connection.getHeaderFields();
                        // for (Map.Entry<String, List<String>> stringListEntry : headerFields.entrySet()) {
                        //     Log.d(TAG, "cfx " + stringListEntry.getKey() + ": " +  stringListEntry.getValue());
                        // }
                        // Log.d(TAG, "cfx " + connection.getHeaderField("Content-disposition"));
                        String headerField = connection.getHeaderField("Content-disposition");
                        int index = headerField.indexOf("filename=");
                        String fileName = headerField.substring(index + "filename=".length()); // 拿到下载的图片名称
                        Log.d(TAG, "cfx fileName = " + fileName);
                        // 拿到文件名称后,创建File,要保存在固定的路径下面
                        // File externalFileDir =
                        //         RequestTestActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES); // 没有权限
                        // Log.d(TAG, "cfx externalFileDir = " + externalFileDir);
                        // 保存到 /storage/self/primary/DCIM/Camera/路径下面
                        String filePath = "/storage/self/primary/DCIM/Camera/" + fileName;
                        Log.d(TAG, "cfx filePath = " + filePath);
                        File file = new File(filePath);
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                        fileOutputStream = new FileOutputStream(file);
                        inputStream = connection.getInputStream();
                        bufferedInputStream= new BufferedInputStream(inputStream);
                        byte[] buffer = new byte[1024];
                        int len;
                        while((len = bufferedInputStream.read(buffer, 0, buffer.length)) != -1) {
                            fileOutputStream.write(buffer, 0, len);
                        }
                        fileOutputStream.flush();
                        Log.d(TAG, "cfx 下载文件成功");
                    }
                } catch (Exception e) {
                    Log.d(TAG, "cfx downloadFile Exception: " + e);
                } finally {
                    CloseIo.CloseIoStream(fileOutputStream);
                    CloseIo.CloseIoStream(inputStream);
                    CloseIo.CloseIoStream(bufferedInputStream);
                }
            }
        }).start();
    }

步骤1:拼接Url获取连接

2、通过connection.getHeaderField("Content-disposition")获取文件名称信息,并进行截取获取文件名

3、构建文件的路径,创建File,创建FileOutputStream

4、通过输入流,进行边读边写,最后关流即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值