CloseableHttpResponse方式
get请求
public String logoutByToken (String token)throws IOException { String code =null; if(token == null){ return "500"; }else { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpPost = new HttpGet("url); CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); String responseResult = EntityUtils.toString(response.getEntity()); JSONObject jsonObject = JSON.parseObject(responseResult); code = jsonObject.getString("code"); System.out.println("logoutByToken:" + responseResult); response.close(); httpClient.close(); } catch (Exception e) { if (response != null) { response.close(); } if (httpClient != null) { httpClient.close(); } } } return code; }
HttpURLConnection方式
public String sendHTTPS(String method, String url, Map<String, String> headerMap, String requestBody) { OutputStream out = null; BufferedReader in = null; try { URL serverUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection(); conn.setRequestMethod(method); conn.setDoOutput(true); conn.setDoInput(true); if (headerMap != null && headerMap.size() > 0) { Set<Map.Entry<String, String>> entries = headerMap.entrySet(); for (Map.Entry<String, String> e : entries) { conn.setRequestProperty(e.getKey(), e.getValue()); } } conn.setInstanceFollowRedirects(false); conn.connect(); if (method.equals("POST") && requestBody != null) { out = conn.getOutputStream(); out.write(requestBody.getBytes("utf-8")); out.flush(); } StringBuffer buffer = new StringBuffer(); in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); String str = null; while ((str = in.readLine()) != null) { buffer.append(str); } return buffer.toString(); } catch (IOException e) { } finally { if (null != out) { try { out.close(); } catch (Exception e) { e.printStackTrace(); } } if (null != in) { try { in.close(); } catch (Exception e) { e.printStackTrace(); } } } return null; } }
HttpUtil方式
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.HttpClientBuilder; import org.apache.http.protocol.HTTP; import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.charset.Charset; /** * 调用接口 * * @author tangyi * @date 2019/9/11 16:43 */ public class HttpUtil { /** * post方式调用接口 * * @param url 远程接口url * @param jsonString JSON参数 * @return String * @throws Exception 异常 */ public static String post(String url, String jsonString) throws Exception { // 打造请求体,设置编码 HttpPost httpPost = new HttpPost(url); httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json; charset=utf-8"); httpPost.addHeader(HTTP.CONTENT_ENCODING, "UTF-8"); // 设置JSON参数 StringEntity entity = new StringEntity(jsonString, Charset.forName("UTF-8")); entity.setContentEncoding("UTF-8"); httpPost.setEntity(entity); // 打造客户端 CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 发送请求,获得结果 HttpResponse response = httpClient.execute(httpPost); // 获取返回结果 HttpEntity entitys = response.getEntity(); BufferedReader in = new BufferedReader(new InputStreamReader(entitys.getContent(), "UTF-8")); StringBuilder buffer = new StringBuilder(); String line; while ((line = in.readLine()) != null) { buffer.append(line); } in.close(); return buffer.toString(); } /** * post方式调用接口 * * @param url 远程接口url * @param jsonString JSON参数 * @return String * @throws Exception 异常 */ public static String postTextPlain(String url, String jsonString) throws Exception { // 打造请求体,设置编码 HttpPost httpPost = new HttpPost(url); httpPost.addHeader(HTTP.CONTENT_TYPE, "text/plain; charset=utf-8"); httpPost.addHeader(HTTP.CONTENT_ENCODING, "UTF-8"); // 设置JSON参数 StringEntity entity = new StringEntity(jsonString, Charset.forName("UTF-8")); entity.setContentEncoding("UTF-8"); httpPost.setEntity(entity); // 打造客户端 CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 发送请求,获得结果 HttpResponse response = httpClient.execute(httpPost); // 获取返回结果 HttpEntity entitys = response.getEntity(); BufferedReader in = new BufferedReader(new InputStreamReader(entitys.getContent(), "UTF-8")); StringBuilder buffer = new StringBuilder(); String line; while ((line = in.readLine()) != null) { buffer.append(line); } in.close(); return buffer.toString(); } }
调用httpUtil String requestJson = JSON.toJSONString(vo); String result = HttpUtil.httpPost(url, requestJson);
public String postData(String url, Map<String, Object> params) throws Exception { //创建post请求对象 HttpPost httppost = new HttpPost(url); // 获取到httpclient客户端 CloseableHttpClient httpclient = HttpClients.createDefault(); try { //创建参数集合 List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); //添加请求头参数 // if(url.equals(GetOlapDataUrl)) { // httppost.addHeader("Content-Type", "application/json"); // httppost.addHeader("accessToken",params.get("accessToken").toString()); // } // 设置请求的一些配置设置,主要设置请求超时,连接超时等参数 RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(200000).setConnectionRequestTimeout(200000).setSocketTimeout(200000) .build(); httppost.setConfig(requestConfig); /** 生产Cookie **/ httppost.setHeader("Cookie","xxxxxx"); //添加参数 httppost.setEntity(new StringEntity(JSONObject.toJSONString(params), ContentType.create("application/json", "utf-8"))); // 请求结果 String resultString = ""; //启动执行请求,并获得返回值 CloseableHttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 获取请求响应结果 HttpEntity entity = response.getEntity(); if (entity != null) { // 将响应内容转换为指定编码的字符串 resultString = EntityUtils.toString(entity, "UTF-8"); System.out.printf("Response content:{}", resultString); return resultString; } } else { System.out.println("请求失败!"); return resultString; } } catch (Exception e) { throw e; } finally { httpclient.close(); } return null; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?