/** * 创建HTTPPOST请求 * * @param url * 请求接口路径 * @param headers * 待添加请求头内容 * @param reqJsonStr * 请求的JSON字符串内容 * @return */ public static Result invoke(String url, Map<String, String> headers, String reqJsonStr) throws IOException { // 创建httppost请求 CloseableHttpClient httpclient = HttpClientBuilder.create().build(); Result result = new Result(); try { HttpPost post = new HttpPost(url);// 请求方法地址 RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(50000) // 设置连接超时时间 .setConnectionRequestTimeout(10000) // REQUEST超时时间 .setSocketTimeout(50000).build(); // 设置读取超时时间 post.setConfig(requestConfig); StringEntity s = new StringEntity(reqJsonStr, Charset.forName("UTF-8")); s.setContentEncoding("UTF-8"); s.setContentType("application/json; charset=utf-8");// 发送json数据需要设置contentType post.setEntity(s); post.setHeader("Accept", "application/json"); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { post.setHeader(entry.getKey(), entry.getValue()); } } HttpResponse response = httpclient.execute(post); // 获取请求结果信息 String content = EntityUtils.toString(response.getEntity()); result.setObj(content); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200时表示成功 result.setSuccess(true); } else { result.setSuccess(false); result.setMsg("HTTP请求发生错误,错误编码:" + response.getStatusLine().getStatusCode()); } } catch (Exception e) { result.setSuccess(false); result.setMsg("请求异常,请联系管理员!"); e.printStackTrace(); } finally { httpclient.close();// 用完以后释放连接 } return result; }
版权声明:本文为leese233原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。