1、新建工具类

package com.hzc.util;import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class HttpClientUtilsExt {protected static org.apache.log4j.Logger log = org.apache.log4j.LogManager.getLogger(HttpClientUtilsExt.class);private HttpClientUtilsExt() {}/*** 使用post方式提交http请求,请求参数默认使用ISO-8859-1编码,需要调用者自己关闭CloseableHttpResponse** @param url    请求地址* @param params 请求参数* @return CloseableHttpResponse* @throws IOException*/public static CloseableHttpResponse post(String url, Map<String, String> params) throws IOException {return post(url, params, null);}/*** 使用post方式提交http请求,需要调用者自己关闭CloseableHttpResponse** @param url     请求地址* @param params  请求参数* @param charset 请求参数编码* @return CloseableHttpResponse* @throws IOException*/public static CloseableHttpResponse post(String url, Map<String, String> params, String charset) throws IOException {CloseableHttpClient httpclient = createSSLClientDefault();HttpPost httpPost = buildHttpPost(url, params, charset);RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();//设置请求和传输超时时间httpPost.setConfig(requestConfig);return httpclient.execute(httpPost);}/*** 构建post请求数据** @param url* @param params* @param charset* @return* @throws UnsupportedEncodingException*/private static HttpPost buildHttpPost(String url, Map<String, String> params, String charset) throws UnsupportedEncodingException {HttpPost httpPost = new HttpPost(url);if (params == null || params.isEmpty()) {return httpPost;}List<NameValuePair> nvps = new ArrayList<NameValuePair>();String value = "";for (String key : params.keySet()) {value = params.get(key) == null ? "" : params.get(key);nvps.add(new BasicNameValuePair(key, value));}if (charset != null) {httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));} else {httpPost.setEntity(new UrlEncodedFormEntity(nvps));}return httpPost;}/*** 使用post方式提交http请求,注意需要调用者自己关闭流** @param url     请求地址* @param params  请求参数* @param charset 参数值的编码格式* @return InputStream 返回输入流* @throws IOException*/public static InputStream postReturnInputStream(String url, Map<String, String> params, String charset) throws IOException {CloseableHttpResponse response = post(url, params, charset);return response.getEntity().getContent();}/*** 使用post方式提交http请求,该方法会自己关闭流** @param url     请求地址* @param params  请求参数* @param charset 参数值的编码格式* @return String 返回报文体* @throws IOException*/public static String postReturnBodyAsString(String url, Map<String, String> params, String charset) throws IOException {String content = "";CloseableHttpResponse response = null;try {response = post(url, params, charset);HttpEntity entity = response.getEntity();content = EntityUtils.toString(entity);} catch (Exception e) {content = e.getMessage();} finally {HttpClientUtils.closeQuietly(response);}return content;}/*** 使用post方式提交http请求,该方法会自己关闭流** @param url     请求地址* @param params  请求参数* @param charset 参数值的编码格式* @return String 返回报文体* @throws IOException*/public static Map<String, String> postReturnBodyAsMap(String url, Map<String, String> params, String charset) throws IOException {String content = "";CloseableHttpResponse response = null;try {response = post(url, params, charset);HttpEntity entity = response.getEntity();content = EntityUtils.toString(entity);} finally {HttpClientUtils.closeQuietly(response);}return getUrlParams(content);}public static Map<String, String> getUrlParams(String param) {Map<String, String> map = new HashMap<String, String>(0);if (StringUtils.isBlank(param)) {return map;}String[] params = param.split("&");for (int i = 0; i < params.length; i++) {String[] p = params[i].split("=");if (p.length == 2) {map.put(p[0], p[1]);}}return map;}/*** 创建信任https协议的请求,若失败则返回默认http协议** @return*/public static CloseableHttpClient createSSLClientDefault() {try {TrustStrategy trustStrategy = new TrustStrategy() {// 信任所有public boolean isTrusted(X509Certificate[] chain, String authType)throws CertificateException {return true;}};SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);return HttpClients.custom().setSSLSocketFactory(sslsf).build();} catch (KeyManagementException e) {log.error("[member-web][HttpClentUtil][CloseableHttpClient]出现异常:", e);} catch (NoSuchAlgorithmException e) {log.error("[member-web][HttpClentUtil][CloseableHttpClient]出现异常:", e);} catch (KeyStoreException e) {log.error("[member-web][HttpClentUtil][CloseableHttpClient]出现异常:", e);}return HttpClients.createDefault();}
}

2、建立请求

Map<String, String> map = new HashMap<String, String>();
map.put("appKey", "691");
map.put("orderInfo", "123");
String url = "http://127.0.0.1:8080/order/submitOrder.html";
String result = HttpClientUtilsExt.postReturnBodyAsString(url, map, "UTF-8");

发送请求使用UTF-8编码方式。

java建立url请求获取数据相关推荐

  1. 【技术应用】java通过url爬虫获取公众号文章内容

    [技术应用]java通过url爬虫获取公众号文章内容 一.前言 二.解决思路 三.爬虫工具 四.代码实现 1.爬取公众号文章 2.爬取CSDN文章 五.总结 一.前言 平时在微信或者钉钉发送消息时,会 ...

  2. java的get请求获取网络中的图片

    写项目的时候写的,感觉以后还会用,所以记录一下 一种通过 java 的get请求获取 网上图片的数据 二种,通过获取本地的具体文件下的图片的数据 前台写的 date.t.avatat 是 存在数据库中 ...

  3. jQuery使用ajax跨域请求获取数据

    jQuery使用ajax跨域请求获取数据 跨域是我在日常面试中经常会问到的问题,这词在前端界出现的频率不低,主要原因还是由于安全限制(同源策略, 即JavaScript或Cookie只能访问同域下的内 ...

  4. java通过url读取pdf数据

    java通过url读取pdf数据 import java.io.*; import java.net.MalformedURLException; import java.net.URL; impor ...

  5. Java 通过Request请求获取IP地址

    Java 通过Request请求获取IP地址 项目需要将不同省份的用户,展示不同内容,所以需要通过Request请求获取IP地址. 先来贴代码, 如果你要在生产环境使用就直接拿去用吧,我这边已经上线了 ...

  6. Promise相关内容(三)——异步获取服务器数据:promise方式解决回调地狱的问题。通过多个.then使代码可读性更高 实现异步任务的串行执行,保证按顺序发送请求获取数据

    Promise相关内容(三)--异步获取服务器数据:promise方式解决回调地狱的问题.通过多个.then使代码可读性更高 & 实现异步任务的串行执行,保证按顺序发送请求获取数据 第一种形式 ...

  7. java通过url读取远程数据并保持到本地

    前几天老姐突然告诉我,她在JD上买了本电子图书,然后买完发现,只能在线或者使用它自己的阅读器看,很不方便,让我给想想办法. 然后我就开始琢磨,最开始,我直接使用Acrobat Reader打开,发现只 ...

  8. ajax中get请求获取数据

    回到文章总目录 1.创建在testtwo文件夹并在这个文件夹里面 2.创建get.html文件 3.创建server.js文件 get.html文件 <!DOCTYPE html> < ...

  9. java通过URL请求实现网上图片下载

    学习一下网络知识和看看大佬的博客,直接贴代码,odk import java.io.*; import java.net.MalformedURLException; import java.net. ...

最新文章

  1. SAP Basis 日常管理
  2. 获取C#中方法的执行时间及其代码注入
  3. java 抽象类,接口,object类详解
  4. 如何设置search parameter的默认operator
  5. 【ArcGIS Pro微课1000例】0002:ArcGIS Pro 2.5二三维联动显示
  6. 无服务器–仅仅是构建现代应用程序的一种方法?
  7. n位数的全排列(需要考虑大数的情况)
  8. 高光谱数据集_文献选读|从地面和空间高光谱数据中提取红边位置参数,以估算水稻冠层叶氮含量...
  9. shrio 权限管理filterChainDefinitions过滤器配置(转)
  10. python--pdb
  11. 【windows核心编程】线程局部存储TLS
  12. Android WebView无法播放视频或直播,关闭界面后任在播放的问题;
  13. tensorflow自定义op_TensorFlow 自定义模型导出:将 .ckpt 格式转化为 .pb 格式
  14. 学而思的python课怎么样_学而思老师怎么样?上课效果好吗?
  15. [转载]Android学习网站
  16. 【牛客练习赛13】 A B C D【康拓展开】 E【DP or 记忆化搜索】 F 【思维】
  17. Maven Nexus详解
  18. 免费视频教程!零基础学Python系列(7) - 数据类型之bytes(上)
  19. 双球坐标系_2.1 天球坐标系和地球坐标系
  20. 美国软件和菜头——《软件随想录》读后感

热门文章

  1. 交叉熵的公式是怎么来的
  2. 兰州大学2018计算机考研复试线,2018年兰州大学考研复试分数线已公布
  3. 区块链共识机制及优缺点
  4. 【IoT】加密与安全:动态密码图解:HOTP 与 TOTP 算法
  5. 面试-浏览器缓存机制
  6. idea 离线安装 Lombok插件
  7. 花若盛開,蝴蝶自來。人若精彩,天自安排。
  8. NYOJ - 盗梦空间
  9. Windows 10 安装安卓子系统 WSA(Magisk/KernelSU)使用 WSA 工具箱安装 APK
  10. ESP32设备驱动-TCS3200颜色传感器驱动