工具类-HTTP连接

JAVA HTTP连接工具类

public class HttpUtils {

    /**
     * 同步get请求
     *
     * @param utl    请求地址
     * @return
     */
    public static JSONObject getExecute(String utl) {
        //获取可关闭的 httpCilent
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //配置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000)
                .setConnectionRequestTimeout(1000)
                .setSocketTimeout(1000)
                .setRedirectsEnabled(true)
                .build();
        //设置URL
        HttpGet httpGet = new HttpGet(utl);
        //设置超时时间
        httpGet.setConfig(requestConfig);
        JSONObject jsonObject = null;
        try {
            //设置post求情参数
            HttpResponse httpResponse = httpClient.execute(httpGet);
            jsonObject = getResult(httpResponse);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close(); //释放资源
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jsonObject;
        }
    }

    /**
     * 同步post请求
     *
     * @param utl    请求地址
     * @param params map类型请求参数
     * @return
     */
    public static JSONObject postExecute(String utl, Map<String, Object> params) {
        //获取可关闭的 httpCilent
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //配置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000)
                .setConnectionRequestTimeout(1000)
                .setSocketTimeout(1000)
                .setRedirectsEnabled(true)
                .build();
        //设置URL
        HttpPost httpPost = new HttpPost(utl);
        //设置超时时间
        httpPost.setConfig(requestConfig);
        JSONObject jsonObject = null;
        try {
            //装配post请求参数
            List<NameValuePair> pairList = new ArrayList<>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue() == null ? "" : entry.getValue().toString());
                pairList.add(pair);
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
            httpPost.setEntity(entity);

            //设置post求情参数
            HttpResponse httpResponse = httpClient.execute(httpPost);
            jsonObject = getResult(httpResponse);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close(); //释放资源
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jsonObject;
        }
    }

    /**
     * 同步put请求
     *
     * @param utl    请求地址
     * @param params map类型请求参数
     * @return
     */
    public static JSONObject putExecute(String utl, Map<String, Object> params) {
        //获取可关闭的 httpCilent
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //配置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000)
                .setConnectionRequestTimeout(1000)
                .setSocketTimeout(1000)
                .setRedirectsEnabled(true)
                .build();
        //设置URL
        HttpPut httpPost = new HttpPut(utl);
        //设置超时时间
        httpPost.setConfig(requestConfig);
        JSONObject jsonObject = null;
        try {
            //装配post请求参数
            List<NameValuePair> pairList = new ArrayList<>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue() == null ? "" : entry.getValue().toString());
                pairList.add(pair);
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
            httpPost.setEntity(entity);

            //设置post求情参数
            HttpResponse httpResponse = httpClient.execute(httpPost);
            jsonObject = getResult(httpResponse);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close(); //释放资源
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jsonObject;
        }
    }

    /**
     * 同步delete请求
     *
     * @param utl    请求地址
     * @return
     */
    public static JSONObject deleteExecute(String utl) {
        //获取可关闭的 httpCilent
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //配置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000)
                .setConnectionRequestTimeout(1000)
                .setSocketTimeout(1000)
                .setRedirectsEnabled(true)
                .build();
        //设置URL
        HttpDelete httpDelete = new HttpDelete(utl);
        //设置超时时间
        httpDelete.setConfig(requestConfig);
        JSONObject jsonObject = null;
        try {
            //设置post求情参数
            HttpResponse httpResponse = httpClient.execute(httpDelete);
            jsonObject = getResult(httpResponse);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close(); //释放资源
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return jsonObject;
        }
    }

    /**
     * 获取结果
     *
     * @param httpResponse
     * @return
     * @throws IOException
     */
    private static JSONObject getResult(HttpResponse httpResponse) throws IOException {
        if (httpResponse != null) {
            String strResult = EntityUtils.toString(httpResponse.getEntity());
            //一个简单方便 的方法将Json文本信息转换为JsonObject对象的同时转换为JavaBean对象!
            JSONObject jsonObject = JSON.parseObject(strResult);
            return jsonObject;
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        String url = "http://127.0.0.1:8080/login/pwdLogin";
        Map map = new HashMap();
        map.put("accountNo", "admin");
        map.put("password", "123456");
        JSONObject jsonObject = postExecute(url, map);
        //System.out.println(((JSONObject)jsonObject.get("obj")).toString());
        // Ddd d = JSONObject.toJavaObject((JSONObject) jsonObject.get("obj"), Ddd.class);
        System.out.println(jsonObject.toString());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值