package com.yd.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class HttpUtil {

    public static String defaultEncoding= "utf-8";
    
    /**
     * 通过url取得文件返回InputStream类型数据
     *
     */
    public static Map<String,Object> getInput(String path) {
        URL url = null;
        InputStream is = null;
        boolean success = true;
        String message = "下载文件成功";
        Map<String,Object> resp = new HashMap<>();

        try {
            url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据.
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();	//得到网络返回的输入流
        } catch (IOException e) {
            success = false;
            message = "下载文件失败";
        } finally {
            resp.put("is", is);
            resp.put("message", message);
            resp.put("success", success);
        }

        return resp;
    }

    /**
     * http交互方法---post请求 json类型
     * @param url 地址
     * @param json  json字符串
     * @return
     */
    public static String postForJson(String url, String json) {
        String responseJson = null;
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        StringEntity entity = new StringEntity(json,defaultEncoding);
        entity.setContentEncoding(defaultEncoding);
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        try {
            HttpResponse response = client.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == 200){
                HttpEntity httpEntity = response.getEntity();
                responseJson = EntityUtils.toString(httpEntity,defaultEncoding);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseJson;
    }
}
