Java工具类--http请求-post

支持各类型报文与参数说明

说明:

  • url : 地址
  • timeout:超时时间 如3秒 3*1000
  • contentType:类型 如
    • application/x-www-form-urlencoded 
    • application/json
    • application/xml
  • requestBody:报文内容 如 
    • application/x-www-form-urlencoded时 为 "key=value&key2=value2"
    • application/json时 为 " \"key\":\"value\",  \"key2\":\"value2\" "
    • application/xml时 为 "<?xml version=\"1.0\" encoding=\"utf-8\" ?><request>" + "<head>" + str_head + "</head>" + "<body>" + str_body + "</body>" + "</request>"
  • encoding:字符编码 如 utf-8

    public static String postJsonBody(String url, int timeout, String contentType, String requestBody, String encoding){
        HttpPost post = new HttpPost(url);
        try {
            post.setHeader("Content-type", contentType);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(timeout)
                    .setConnectTimeout(timeout)
                    .setConnectionRequestTimeout(timeout)
                    .setExpectContinueEnabled(false).build();
            post.setConfig(requestConfig);

            post.setEntity(new StringEntity(requestBody, encoding));
            logger.info("[HttpUtils Post] begin invoke url:" + url + " , params:" + requestBody);
            CloseableHttpResponse response = httpclient.execute(post);
            try {
                HttpEntity entity = response.getEntity();
                try {
                    if(entity != null){
                        String str = EntityUtils.toString(entity, encoding);
                        logger.info("[HttpUtils Post]Debug response, url :" + url + " , response string :"+str);
                        return str;
                    }
                } finally {
                    if(entity != null){
                        entity.getContent().close();
                    }
                }
            } finally {
                if(response != null){
                    response.close();
                }
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("UnsupportedEncodingException", e);
        } catch (Exception e) {
            logger.error("Exception", e);
        } finally {
            post.releaseConnection();
        }
        return "";
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是一个Java HTTPS请求的通用工具类示例: ``` import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.URL; import java.security.cert.X509Certificate; import java.util.Map; public class HttpsUtil { public static String sendPostRequest(String url, Map<String, String> params) throws Exception { // 创建SSLContext对象,并使用我们指定的信任管理器初始化 TrustManager[] trustManagers = {new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } }}; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManagers, new java.security.SecureRandom()); // 打开连接 URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); con.setSSLSocketFactory(sslContext.getSocketFactory()); // 设置请求头 con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "Mozilla/5.0"); // 设置请求参数 String urlParameters = ""; if (params != null && !params.isEmpty()) { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { if (sb.length() > 0) { sb.append("&"); } sb.append(entry.getKey()).append("=").append(entry.getValue()); } urlParameters = sb.toString(); } // 发送POST请求 con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); // 读取响应 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } } ``` 这个工具类可以在HTTPS请求中使用,会自动忽略SSL证书验证。使用时只需要调用sendPostRequest方法,传入URL和请求参数即可。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShyTan

喜欢的给点打赏呗,纯手打

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值