package cn.iocoder.yudao.module.system.util.http;

import cn.iocoder.yudao.module.system.util.SSLClient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.imageio.ImageIO;
import javax.net.ssl.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

/**
 * Http请求
 */
public class HttpClientUtil {

	private static String CHARSET ="UTF-8";

    public static void main(String[] args) throws Exception{
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Map<String, String> map = new HashMap<>();
        map.put("devID", "ecfabcadebeb");
        map.put("APPID", "RqPboxwKSORYykCn33");
        String url = "http://api.sleepthing.com/info/getDeviceNetworkState";
//        String doGet = doGet(url, map);
//        System.out.println("请求数据：");
//        System.out.println(JSON.toJSONString(map));
//        System.out.println("数据返回：");
//        System.out.println(doGet);http://39.98.82.44/group1/M00/00/11/rBoolVz3KDqANhpmAAAi5L-GLkA208.png
        String token = "27_edGhq70Pv_2ir8Q3bUcgCPhPSSAkY_JU2XQRuUIDwHt9uInpiaEWKdvMah-j37wTwy1p5xOHOQbJg8EwnHbhNi6Jkv4TQpA5qWe4UZgZni1H5xOl5pud7G5O7mjYz_U_O2J4lGYRSdGgLSA9LQQhADAWBB";
//        String img = getMediaIdFromUrl("http://39.98.82.44/group1/M00/00/11/rBoolVz3KDqANhpmAAAi5L-GLkA208.png", "image", token);
        String img = getMediaIdFromUrl("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFU8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAySjNBUDlKS184Rl8xTm5CbE50Y08AAgRHF9VdAwQQDgAA", "image", token);
        System.out.println(img);
//        String wxaCode = getWxaCode("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQFU8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAySjNBUDlKS184Rl8xTm5CbE50Y08AAgRHF9VdAwQQDgAA", "");
//        System.out.println(wxaCode);
    }

    public static String doGet(String url, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key).toString());
                }
            }
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);

            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {// 判断返回状态是否为200
                resultString = EntityUtils.toString(response.getEntity(), CHARSET);
            }else{
            	resultString = EntityUtils.toString(response.getEntity(), CHARSET);
            	throw new RuntimeException(resultString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static HttpClientResult doGet(String url, Map<String, String> param, String encoding) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key).toString());
                }
            }
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            response = httpclient.execute(httpGet);
            if(response != null && response.getStatusLine() != null) {
                String content = "";
                if(response.getEntity() != null) {
                    encoding = StringUtils.isNotBlank(encoding) ? encoding : CHARSET;
                    content = EntityUtils.toString(response.getEntity(), encoding);
                }
                return new HttpClientResult(response.getStatusLine().getStatusCode(), content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }


    public static String doPut(String url, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key).toString());
                }
            }
            URI uri = builder.build();
            HttpPut httpPut = new HttpPut(uri);
            response = httpclient.execute(httpPut);
            if (response.getStatusLine().getStatusCode() == 200) {// 判断返回状态是否为200
                resultString = EntityUtils.toString(response.getEntity(), CHARSET);
            }else{
                resultString = EntityUtils.toString(response.getEntity(), CHARSET);
                throw new RuntimeException(resultString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doHttpsPostJson(String url,String json)
	{
    	 HttpClient httpClient = null;
         HttpPost httpPost = null;
         String result = null;
         try
         {
         	httpClient = new SSLClient();
             httpPost = new HttpPost(url);
             StringEntity se = new StringEntity(json.toString(),"UTF-8");
             se.setContentType("application/json");
             se.setContentEncoding(new BasicHeader("text/json", "application/json"));
             httpPost.setEntity(se);
             HttpResponse response = httpClient.execute(httpPost);
             if(response != null)
             {
                 HttpEntity resEntity = response.getEntity();
                 if(resEntity != null)
                 {
                     result = EntityUtils.toString(resEntity,"UTF-8");
                 }
             }
         }catch(Exception ex)
         {
             ex.printStackTrace();
         }
         return result;
    }
    
    public static String sendPost(String url, String param){
    	PrintWriter out = null;
        BufferedReader in = null;
        URLConnection conn = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            //conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
                if(conn!=null){
                	//conn.
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
       
    }

    public static String doPost(String url, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)+""));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, CHARSET);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static HttpClientResult doPost(String url, Map<String, String> param, String encoding) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)+""));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, CHARSET);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            if(response != null && response.getStatusLine() != null) {
                String content = "";
                if(response.getEntity() != null) {
                    encoding = StringUtils.isNotBlank(encoding) ? encoding : CHARSET;
                    content = EntityUtils.toString(response.getEntity(), encoding);
                }
                return new HttpClientResult(response.getStatusLine().getStatusCode(), content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }


    public static String doPost(String url) {
        return doPost(url, null);
    }

    /**
     * 请求的参数类型为json
     * @param url
     * @param json {username:"",pass:""}
     * @return
     */
    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static HttpClientResult doPostJson(String url, String json, String encoding) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);

            if(response != null && response.getStatusLine() != null) {
                String content = "";
                if(response.getEntity() != null) {
                    encoding = StringUtils.isNotBlank(encoding) ? encoding : CHARSET;
                    content = EntityUtils.toString(response.getEntity(), encoding);
                }
                return new HttpClientResult(response.getStatusLine().getStatusCode(), content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }


    public static String getWxaCode(String url, String json){
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultFile = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();
            Header[] headers = response.getHeaders("Content-Type");
            if(!"image/jpeg".equals(headers[0].getValue())){
                String resultString = EntityUtils.toString(response.getEntity(), CHARSET);
                throw new RuntimeException(resultString);
            }
            saveToImgByInputStream(inputStream, "/root/pk_dir/java/temp/img", "wxaqrcode.png");
            File tmpFile = new File("/root/pk_dir/java/temp/img", "wxaqrcode.png");
            FileInputStream fileInputStream = new FileInputStream(tmpFile);
            Map<String, String> map = new HashMap<>();
            map.put("filename", "wxa_qrcode_.png");
            //resultFile = FastDFSUtil.uploadFileWithMultipart(fileInputStream, map);
//            UploadResultVO uploadResultVO = GoUploadUtil.upload(tmpFile);
//            resultFile = uploadResultVO.getPath();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultFile;
    }

    /**
     * 将二进制转换成文件保存
     * @param instreams 二进制流
     * @param imgPath 图片的保存路径
     * @param imgName 图片的名称
     * @return
     *      1：保存正常
     *      0：保存失败
     */
    public static int saveToImgByInputStream(InputStream instreams,String imgPath,String imgName){
        int stateInt = 1;
        if(instreams != null){
            try {
                File file=new File(imgPath);//可以是任何图片格式.jpg,.png等
                if(!file.exists()){
                    file.mkdir();
                }
                FileOutputStream fos=new FileOutputStream(imgPath+"/"+imgName);
                byte[] b = new byte[1024];
                int nRead = 0;
                while ((nRead = instreams.read(b)) != -1) {
                    fos.write(b, 0, nRead);
                }
                fos.flush();
                fos.close();
            } catch (Exception e) {
                stateInt = 0;
                e.printStackTrace();
            } finally {
            }
        }
        return stateInt;
    }
    
    /**
	 * 发送HTTPS	POST请求
	 * 要访问的HTTPS地址,POST访问的参数Map对象
	 * @param
	 * @return  返回响应值
	 * */
	public static final String doPosts(String url, Map<String, String> params) {
		String responseContent = null;
		HttpClient httpClient =HttpClients.createDefault();// new DefaultHttpClient();
		//创建TrustManager
		X509TrustManager xtm = new X509TrustManager() {
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		//这个好像是HOST验证
		X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
			public boolean verify(String arg0, SSLSession arg1) {
				return true;
			}
			public void verify(String arg0, SSLSocket arg1) throws IOException {}
			public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {}
			public void verify(String arg0, X509Certificate arg1) throws SSLException {}
		};
		try {
			//TLS1.0与SSL3.0基本上没有太大的差别，可粗略理解为TLS是SSL的继承者，但它们使用的是相同的SSLContext
			SSLContext ctx = SSLContext.getInstance("TLS");
			//使用TrustManager来初始化该上下文，TrustManager只是被SSL的Socket所使用
			ctx.init(null, new TrustManager[] { xtm }, null);
			//创建SSLSocketFactory
			SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
			socketFactory.setHostnameVerifier(hostnameVerifier);
			//通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
			httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参数
			for (Map.Entry<String, String> entry : params.entrySet()) {
				formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(formParams,CHARSET));
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity(); // 获取响应实体
			if (entity != null) {
				responseContent = EntityUtils.toString(entity, CHARSET);
			}
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			httpClient.getConnectionManager().shutdown();
		}
		return responseContent;
	}
	public static String request2WeiXin(String url, String requestMethod,
			String params) throws Exception {
		StringBuffer json = new StringBuffer();
		URL realUrl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
		conn.setConnectTimeout(30000);// 30秒超时
		conn.setReadTimeout(30000);// 30秒读取超时
		conn.setRequestMethod(requestMethod);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.connect();
		if (params != null && !params.equals("")) {
			/*
			 * // 获取URLConnection对象对应的输出流 OutputStreamWriter out = new
			 * OutputStreamWriter(conn.getOutputStream()); // 发送请求参数
			 * out.write(URLEncoder.encode(params,"UTF-8")); out.write(new
			 * String (params.getBytes("UTF-8"))); out.flush(); out.close();
			 */

			OutputStream out = conn.getOutputStream();
			out.write(params.getBytes("UTF-8"));
			out.flush();
			out.close();
		}
		InputStream is = conn.getInputStream();
		BufferedReader bf = new BufferedReader(new InputStreamReader(is,
				"UTF-8"));
		String valueString = null;
		while ((valueString = bf.readLine()) != null)
			json.append(valueString);
		// System.out.println(json.toString());
		is.close();
		if (conn != null)
			conn.disconnect();
		System.gc();
		return json.toString();
	}
	/**
     * 网络图片上传到微信服务器
     *
     * @param urlPath 图片路径
     * @return JSONObject
     * @throws Exception
     */
    public static String getMediaIdFromUrl(String urlPath, String fileType, String token) throws Exception {
        String result = null;
        String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+ token +"&type=" + fileType;
        String fileName = "ss.jpg";
        // 获取网络图片
        URL mediaUrl = new URL(urlPath);
        HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
        meidaConn.setDoOutput(true);
        meidaConn.setRequestMethod("GET");

        /**
         * 第一部分
         */
        URL urlObj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
        con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false); // post方式不能使用缓存
        // 设置请求头信息
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        // 设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        // 请求正文信息
        // 第一部分：
        StringBuilder sb = new StringBuilder();
        sb.append("--"); // 必须多两道线
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + fileName + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        byte[] head = sb.toString().getBytes("utf-8");
        // 获得输出流
        OutputStream out = new DataOutputStream(con.getOutputStream());
        // 输出表头
        out.write(head);
        // 文件正文部分
        // 把文件已流文件的方式 推入到url中
        System.out.println(meidaConn.getInputStream());
        BufferedImage bufferedImage = ImageIO.read(meidaConn.getInputStream());
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", byteArrayOut);
        System.out.println(bufferedImage);
        System.out.println("--------------------------------------");
//        System.out.println(byteArrayOut);


        byte[] resultingBytes = byteArrayOut.toByteArray();
        ByteArrayInputStream byteArrayInputStream2 = new ByteArrayInputStream(resultingBytes);
//        System.out.println(byteArrayInputStream2);
//        BufferedImage bufferedImage1 = ImageIO.read(byteArrayInputStream2);
//        ImageIO.write(bufferedImage1, "jpg", new File("E:\\tmp\\dd.jpg"));
//        FileInputStream fileInputStream = new FileInputStream(new File("E:\\tmp\\", "dd.jpg"));
        DataInputStream in = new DataInputStream(byteArrayInputStream2);
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();
        // 结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
        out.write(foot);
        out.flush();
        out.close();
        meidaConn.disconnect();
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        try {
            // 定义BufferedReader输入流来读取URL的响应
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            if (result == null) {
                result = buffer.toString();
            }
        } catch (IOException e) {
//            log.info("发送POST请求出现异常！ {}", e);
            e.printStackTrace();
            throw new IOException("数据读取异常");
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        JSONObject jsonObj = JSON.parseObject(result);
        System.out.println(jsonObj);
//        log.info("getMediaId jsonObj: {}", jsonObj);
        return jsonObj.getString("media_id");
    }
    public static String decodeNetworkImg(String urlPath) {
        BufferedImage image;
//        try {
//            // 获取网络图片
//            URL mediaUrl = new URL(urlPath);
//            HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
//            meidaConn.setDoOutput(true);
//            meidaConn.setRequestMethod("GET");
//            image = ImageIO.read(meidaConn.getInputStream());
//            LuminanceSource source = new BufferedImageLuminanceSource(image);
//            Binarizer binarizer = new HybridBinarizer(source);
//            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
//            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
//            //解码设置编码方式为：UTF-8
//            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
//            //优化精度
//            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
//            //复杂模式，开启PURE_BARCODE模式
//            hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
//            Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
//            return result.getText();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return null;
    }
    /**
     * 字节数组转成16进制表示格式的字符串
     *
     * @param byteArray
     *            需要转换的字节数组
     * @return 16进制表示格式的字符串
     **/
    private static String toHexString(byte[] byteArray) {
        StringBuilder hexString = new StringBuilder();
        for (byte aByteArray : byteArray) {
            if ((aByteArray & 0xff) < 0x10) {
                hexString.append("0");
            }
            hexString.append(Integer.toHexString(0xFF & aByteArray));
        }
        return hexString.toString().toLowerCase();
    }
    /**
     * 把文件上传到指定url上去
     * @param url 上传地址
     * @param file 待上传文件
     */
    public static JSONObject uploadFile(String url, InputStream file,String fileName) throws IOException{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost(url);

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build();
            httppost.setConfig(requestConfig);

            /**
             * 这一步最关键：
             *调用addBinaryBody("media",input2byte(file),ContentType.DEFAULT_BINARY, fileName),
             * fileName可以为任意值，但不能为null，如果为null则上传失败。
             * input2byte(file)：把inputstream转为byte[]，
             * 如果直接调用addPart用FileBody做参数，则MultifilePart不好转换；
             * 如果直接调用addPart用InpustreamBody做参数，则因为没有fileName会造成上传失败
             */
            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addBinaryBody("media", input2byte(file), ContentType.DEFAULT_BINARY,
                            fileName).build();

            httppost.setEntity(reqEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    String responseEntityStr = EntityUtils.toString(response.getEntity());
//                    log.info("responseEntityStr=[{}]",responseEntityStr);
                    System.out.println(responseEntityStr);
                    return  JSON.parseObject(responseEntityStr);
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    private static final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }
}
