尧图网络科技YAOTU DIGITAL 获取报价
获取报价
首页 / 资讯中心 / 文章详情

Java post 和 get 请求

发布时间:2026/9/24 18:45:27

资讯中心
01
ARTICLE

Java post 和 get 请求

Java post 和 get 请求
get 请求/** * Get请求 带headers的get请求 */publicStringgetResponse(String url,MapString,Stringheaders){try(CloseableHttpClient httpClientHttpClients.createDefault()){HttpGet requestnewHttpGet(URI.create(url));if(headers!null){for(Map.EntryString,Stringentry:headers.entrySet()){request.setHeader(entry.getKey(),entry.getValue());}}try(CloseableHttpResponse responsehttpClient.execute(request)){HttpEntity entityresponse.getEntity();returnentity!null?EntityUtils.toString(entity,StandardCharsets.UTF_8):null;}catch(Exception ex){thrownewBusinessException(url发送接口请求异常ex.getMessage());}}catch(Exception ex){thrownewBusinessException(Get请求异常ex.getMessage());}}post 请求/** * 绕过验证SSL证书 */privateCloseableHttpClientgetCloseableHttpClient(String httpUrl){CloseableHttpClient clientnull;if(httpUrl.startsWith(https)){try{// 创建 SSLContext // 信任所有证书SSLContext sslContextSSLContextBuilder.create().loadTrustMaterial((x,y)-true).build();// 创建 HttpClient // 信任所有主机名clientHttpClientBuilder.create().setSSLContext(sslContext).setSSLHostnameVerifier((hostname,session)-true).build();}catch(Exception e){clientHttpClients.createDefault();returnclient;}}else{clientHttpClients.createDefault();}returnclient;}/** * post请求 * * param url 请求地址 * param postData 请求参数 * param headers 请求头 */publicStringpostResponse(String url,String postData,MapString,Stringheaders){try(CloseableHttpClient httpClientgetCloseableHttpClient(url)){// 创建HttpPost实例HttpPost httpPostnewHttpPost(url);if(headers!null){for(String key:headers.keySet()){httpPost.addHeader(key,headers.get(key));}}//设置参数和请求格式StringEntity entitynewStringEntity(postData,StandardCharsets.UTF_8);entity.setContentType(application/json; charsetutf-8);httpPost.setEntity(entity);// 发送请求并获取响应try(CloseableHttpResponse responsehttpClient.execute(httpPost)){HttpEntity httpEntityresponse.getEntity();try{if(httpEntity!null){returnEntityUtils.toString(httpEntity,StandardCharsets.UTF_8);}else{returnnull;}}catch(Exception ex){thrownewBusinessException(请求序列化异常ex.getMessage());}}catch(Exception ex){thrownewBusinessException(发送接口请求异常url);}}catch(Exception ex){thrownewBusinessException(接口请求异常url);}}
02
RELATED NEWS

相关资讯

更多网站建设与数字化升级内容

03
WHY YAOTU

想打造同款高转化官网?

懂行业、懂生意,从建站到增长一站式陪跑

场景化定制

不做模板站,围绕你的业务场景量身设计,小众不撞款。

营销型架构

以转化目标组织内容与路径,让官网真正带来询盘。

全周期服务

设计、开发、运营、运维一体,上线只是开始。

免费获取你的建站方案

留下需求,专属顾问 24 小时内为你输出方案建议。