package com.cftech.core.util;

/**
 * Created by faye on 2017/8/31.
 */

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionUtil {

    // 通过get请求得到读取器响应数据的数据流
    public static InputStream getInputStreamByGet(String url) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url)
                    .openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                return inputStream;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    // 通过get请求得到读取器响应数据的数据流
    public static byte[] getByteInputStreamByGet(String url) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url)
                    .openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                byte[] buff = new byte[100];
                int rc = 0;
                while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                return swapStream.toByteArray();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 将服务器响应的数据流存到本地文件
    public static void saveData(InputStream is, File file) {
        try (BufferedInputStream bis = new BufferedInputStream(is);
             BufferedOutputStream bos = new BufferedOutputStream(
                     new FileOutputStream(file))) {
            byte[] buffer = new byte[4096];
            int len = -1;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
                bos.flush();
            }
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static  void main(String[] args){

        /*try {
            String url = "http://car2.autoimg.cn/cardfs/brand/50/g16/M05/5B/78/autohomecar__wKgH11cVh1WADo76AAAK8dMrElU714.jpg";
            String[] split = url.split("\\/");
            String fileName = split[split.length - 1];
            File file = new File("f:/", fileName);

            InputStream inputStream = HttpURLConnectionUtil
                    .getInputStreamByGet(url);
            HttpURLConnectionUtil.saveData(inputStream, file);
        }catch (Exception e){
            e.printStackTrace();
        }*/

    }
}