apache httpclient新版本的get/post请求
来源:互联网 发布:leslie矩阵是什么 编辑:程序博客网 时间:2024/04/29 21:17
直接撸代码
public final class HttpUtils { private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class); private HttpUtils(){} /** * get请求 * @param url * @param headers * @return */ public static String get(String url, Map<String,String> headers) { HttpGet httpGet = new HttpGet(url); headers.entrySet().forEach(entry -> httpGet.addHeader(entry.getKey(), entry.getValue())); return executeRequest(httpGet); } /** * post请求 * @param url * @param headers * @param params 参数 * @return */ public static String post(String url, Map<String,String> headers, Map<String,Object> params) { return post(url, headers, JSON.toJSONString(params)); } /** * post请求 * @param url * @param headers * @param jsonParams 参数,json格式 * @return */ public static String post(String url, Map<String,String> headers, String jsonParams) { HttpPost httpPost = new HttpPost(url); headers.entrySet().forEach(entry -> httpPost.addHeader(entry.getKey(), entry.getValue())); HttpEntity httpEntity = new StringEntity(jsonParams, "utf-8"); httpPost.setEntity(httpEntity); return executeRequest(httpPost); } /** * 执行请求 * @param request * @return */ public static String executeRequest(final HttpUriRequest request) { String result = ""; CloseableHttpClient httpClient = HttpClients.createDefault(); try { result = httpClient.execute(request, response -> { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + statusCode); } }); } catch (IOException e) { e.printStackTrace(); logger.error("url: {}, request failed!", request.getURI().getHost() + request.getURI().getPath()); logger.error("",e); } finally { closeHttpClient(httpClient); } return result; } public static void closeHttpClient(CloseableHttpClient httpClient) { try { httpClient.close(); } catch (IOException e) { logger.error("",e); } }}
阅读全文
0 0
- apache httpclient新版本的get/post请求
- android使用Apache HttpClient实现get/post的请求
- 使用Apache HttpClient发送get、post请求
- Httpclient的Get请求和Post请求
- HttpClient的Get请求和Post请求
- httpClient post/get请求。
- HttpClient get,Post请求
- HttpClient get、post请求
- httpclient的get和post请求
- HttpClient的Post与Get请求
- HttpClient的get和post请求数据
- HttpClient 的post和get请求
- httpClient的Get和Post请求
- HttpClient的post和get请求
- 【Java】HttpURLConnection,HttpClient 的 Get,Post 请求
- httpclient的get和post请求
- HttpClient的GET和POST请求
- Android用Apache HttpClient 实现POST和Get请求
- hihocoder #1338 A Game
- from表单
- grep常用操作
- local_bh_disable, preempt_disable, local_irq_disable
- linux下 Jdk版本切换
- apache httpclient新版本的get/post请求
- 浅谈Ajax
- java 导出Excel 转图片地址为图片
- 【单片机笔记】STM8S系列单片机FLASH操作
- github clone报错Conection refused
- C++ 获取程序运行时间/时间戳 精确到毫秒
- git使用MERGING处理
- 下载功能
- 预处理、结构体