简单工具类HttpUtils

简单记录   工具类HttpUtils

public class HttpUtils {

    public static JSONObject getHttpResponseJson(String url, Map<String, String> param) {
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        JSONObject jsonObject = null;

        try {
            //请求发起客户端
            httpclient = HttpClients.createDefault();
            //参数集合
            List postParams = new ArrayList();
            //遍历参数并添加到集合
            if (param != null) {
                for (Map.Entry<String, String> entry : param.entrySet()) {
                    postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            //通过post方式访问
            HttpPost post = new HttpPost(url);

            HttpEntity paramEntity = new UrlEncodedFormEntity(postParams, "UTF-8");
            post.setEntity(paramEntity);
            response = httpclient.execute(post);
            HttpEntity valueEntity = response.getEntity();
            String content = EntityUtils.toString(valueEntity);
            jsonObject = JSONObject.parseObject(content);

            return jsonObject;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return jsonObject;
    }

    /**
     * 以get方式调用第三方接口
     * @param url
     * @return
     */
    public static String doGet(String url, String AccessToken){
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        try {
            get.addHeader("Authorization", AccessToken);
            get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            HttpResponse response = httpClient.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String doGet(String url){
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        try {
            //get.addHeader("Authorization", AccessToken);
            get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            HttpResponse response = httpClient.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * Json格式提交数据到第三方接口,并返回数据
     *
     * @param param 第三方接口地址
     * @param param 数据参数,JSON格式,可以为null
     */
    public static String doPost(String urlStr, String param) {
        HttpURLConnection connection = null;
        InputStream is = null;
        InputStreamReader rsd = null;
        BufferedReader br = null;
        OutputStream os = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        StringBuffer sb = new StringBuffer();

        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);    //不缓存
            connection.setRequestProperty("connection", "Keep-Alive");    //设置保活连接
            connection.setRequestProperty("charset", "UTF-8");            //提交的数据编码
            connection.setRequestProperty("Content-type", "application/json");    //提交的数据格式
            connection.setRequestProperty("accept", "application/json");        //接收的数据格式
            connection.setConnectTimeout(30000);    //30秒连接超时
            connection.setReadTimeout(30000);        //30秒读取超时
            connection.connect();
            if (param != null && !"".equals(param)) {
                os = connection.getOutputStream();
                osw = new OutputStreamWriter(os);
                bw = new BufferedWriter(osw);
                bw.write(param);
                bw.flush();
            }
            int status = connection.getResponseCode();
            if (status == 200) {
                is = connection.getInputStream();
                rsd = new InputStreamReader(is, "UTF-8");
                br = new BufferedReader(rsd);
                String s;
                while ((s = br.readLine()) != null) {
                    sb.append(s);
                }
            } else {
                return "{\"ResuleState\":\"-1\",\"Msg\":\"连接异常\"}";
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) br.close();
                if (rsd != null) rsd.close();
                if (is != null) is.close();
                if (bw != null) bw.close();
                if (osw != null) osw.close();
                if (os != null) os.close();
                if (connection != null) connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值