最近差点被业务逻辑搞懵逼,果然要先花时间思考,确定好流程再执行。目前最好用的jar包还是org.apache.http。

  1. public class HttpClientHelper {
  2.  
  3. private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)
  4. .setConnectionRequestTimeout(15000).build();
  5.  
  6. private static HttpClientHelper instance = null;
  7.  
  8. public HttpClientHelper() {
  9. }
  10.  
  11. public static HttpClientHelper getInstance() {
  12. if (instance == null) {
  13. instance = new HttpClientHelper();
  14. }
  15. return instance;
  16. }
  17.  
  18. /**
  19. * 发送 post请求
  20. *
  21. * @param httpUrl
  22. * 地址
  23. */
  24. public String sendHttpPost(String httpUrl) {
  25. HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
  26. return sendHttpPost(httpPost);
  27. }
  28.  
  29. /**
  30. * 发送 post请求
  31. *
  32. * @param httpUrl
  33. * 地址
  34. * @param params
  35. * 参数(格式:key1=value1&key2=value2)
  36. */
  37. public String sendHttpPost(String httpUrl, String params) {
  38. HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
  39. try {
  40. // 设置参数
  41. StringEntity stringEntity = new StringEntity(params, "UTF-8");
  42. stringEntity.setContentType("application/x-www-form-urlencoded");
  43. httpPost.setEntity(stringEntity);
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. }
  47. return sendHttpPost(httpPost);
  48. }
  49.  
  50. /**
  51. * 发送 post请求
  52. *
  53. * @param httpUrl
  54. * 地址
  55. * @param maps
  56. * 参数
  57. */
  58. public String sendHttpPost(String httpUrl, Map<String, String> maps) {
  59. HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
  60. // 创建参数队列
  61. List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
  62. for (String key : maps.keySet()) {
  63. nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
  64. }
  65. try {
  66. httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
  67. } catch (Exception e) {
  68. e.printStackTrace();
  69. }
  70. return sendHttpPost(httpPost);
  71. }
  72.  
  73. /**
  74. * 发送 post请求(带文件)
  75. *
  76. * @param httpUrl
  77. * 地址
  78. * @param maps
  79. * 参数
  80. * @param fileLists
  81. * 附件
  82. */
  83. public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
  84. HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
  85. MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
  86. if (maps != null) {
  87. for (String key : maps.keySet()) {
  88. meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
  89. }
  90. }
  91. if (fileLists != null) {
  92. for (File file : fileLists) {
  93. FileBody fileBody = new FileBody(file);
  94. meBuilder.addPart("files", fileBody);
  95. }
  96. }
  97. HttpEntity reqEntity = meBuilder.build();
  98. httpPost.setEntity(reqEntity);
  99. return sendHttpPost(httpPost);
  100. }
  101.  
  102. /**
  103. * 发送Post请求
  104. *
  105. * @param httpPost
  106. * @return
  107. */
  108. private String sendHttpPost(HttpPost httpPost) {
  109. CloseableHttpClient httpClient = null;
  110. CloseableHttpResponse response = null;
  111. HttpEntity entity = null;
  112. String responseContent = null;
  113. try {
  114. // 创建默认的httpClient实例.
  115. httpClient = HttpClients.createDefault();
  116. httpPost.setConfig(requestConfig);
  117. // 执行请求
  118. response = httpClient.execute(httpPost);
  119. entity = response.getEntity();
  120. responseContent = EntityUtils.toString(entity, "UTF-8");
  121. } catch (Exception e) {
  122. e.printStackTrace();
  123. } finally {
  124. try {
  125. // 关闭连接,释放资源
  126. if (response != null) {
  127. response.close();
  128. }
  129. if (httpClient != null) {
  130. httpClient.close();
  131. }
  132. } catch (IOException e) {
  133. e.printStackTrace();
  134. }
  135. }
  136. return responseContent;
  137. }
  138.  
  139. public String sendJsonHttpPost(String url, String json) {
  140.  
  141. CloseableHttpClient httpclient = HttpClients.createDefault();
  142. String responseInfo = null;
  143. try {
  144. HttpPost httpPost = new HttpPost(url);
  145. httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
  146. ContentType contentType = ContentType.create("application/json", CharsetUtils.get("UTF-8"));
  147. httpPost.setEntity(new StringEntity(json, contentType));
  148. CloseableHttpResponse response = httpclient.execute(httpPost);
  149. HttpEntity entity = response.getEntity();
  150. int status = response.getStatusLine().getStatusCode();
  151. if (status >= 200 && status < 300) {
  152. if (null != entity) {
  153. responseInfo = EntityUtils.toString(entity);
  154. }
  155. }
  156. } catch (Exception e) {
  157. e.printStackTrace();
  158. } finally {
  159. try {
  160. httpclient.close();
  161. } catch (IOException e) {
  162. e.printStackTrace();
  163. }
  164. }
  165. return responseInfo;
  166. }
  167.  
  168. /**
  169. * 发送 get请求
  170. *
  171. * @param httpUrl
  172. */
  173. public String sendHttpGet(String httpUrl) {
  174. HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
  175. return sendHttpGet(httpGet);
  176. }
  177.  
  178. /**
  179. * 发送 get请求Https
  180. *
  181. * @param httpUrl
  182. */
  183. public String sendHttpsGet(String httpUrl) {
  184. HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
  185. return sendHttpsGet(httpGet);
  186. }
  187.  
  188. /**
  189. * 发送Get请求
  190. *
  191. * @param httpGet
  192. * @return
  193. */
  194. private String sendHttpGet(HttpGet httpGet) {
  195. CloseableHttpClient httpClient = null;
  196. CloseableHttpResponse response = null;
  197. HttpEntity entity = null;
  198. String responseContent = null;
  199. try {
  200. // 创建默认的httpClient实例.
  201. httpClient = HttpClients.createDefault();
  202. httpGet.setConfig(requestConfig);
  203. // 执行请求
  204. response = httpClient.execute(httpGet);
  205. entity = response.getEntity();
  206. responseContent = EntityUtils.toString(entity, "UTF-8");
  207. } catch (Exception e) {
  208. e.printStackTrace();
  209. } finally {
  210. try {
  211. // 关闭连接,释放资源
  212. if (response != null) {
  213. response.close();
  214. }
  215. if (httpClient != null) {
  216. httpClient.close();
  217. }
  218. } catch (IOException e) {
  219. e.printStackTrace();
  220. }
  221. }
  222. return responseContent;
  223. }
  224.  
  225. /**
  226. * 发送Get请求Https
  227. *
  228. * @param httpGet
  229. * @return
  230. */
  231. private String sendHttpsGet(HttpGet httpGet) {
  232. CloseableHttpClient httpClient = null;
  233. CloseableHttpResponse response = null;
  234. HttpEntity entity = null;
  235. String responseContent = null;
  236. try {
  237. // 创建默认的httpClient实例.
  238. PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader
  239. .load(new URL(httpGet.getURI().toString()));
  240. DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
  241. httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
  242. httpGet.setConfig(requestConfig);
  243. // 执行请求
  244. response = httpClient.execute(httpGet);
  245. entity = response.getEntity();
  246. responseContent = EntityUtils.toString(entity, "UTF-8");
  247. } catch (Exception e) {
  248. e.printStackTrace();
  249. } finally {
  250. try {
  251. // 关闭连接,释放资源
  252. if (response != null) {
  253. response.close();
  254. }
  255. if (httpClient != null) {
  256. httpClient.close();
  257. }
  258. } catch (IOException e) {
  259. e.printStackTrace();
  260. }
  261. }
  262. return responseContent;
  263. }
  264.  
  265. public static void main(String[] args) {
  266. HttpClientHelper h = new HttpClientHelper();
  267. Map map = new HashMap();
  268. map.put("messageid", "test00201612210002");
  269. map.put("clientid", "test00");
  270. map.put("index_id", "买方会员");
  271. map.put("threshold", 0.9);
  272. List<String> data = new ArrayList<String>();
  273. data.add("wo xiang cha xun jin tian de yao pin jia ge lie biao");
  274. map.put("data", data);
  275.  
  276. String json = JSON.toJSONString(map);
  277.  
  278. String reply = h.sendJsonHttpPost("http://11.11.40.63:7777/algor/simclassify", json);
  279. System.out.println("reply->"+reply);
  280. }
  281. }

java里遍历动态key:

  1. LinkedHashMap<String, String> jsonMap = JSON.parseObject(jsonStr,new TypeReference<LinkedHashMap<String, String>>() {});
  2. for (Map.Entry<String, String> entry : jsonMap.entrySet()) {
  3. if (Float.valueOf(entry2.getValue()) > tempValue) {
  4. key = entry.getKey());
  5. value= entry.getValue();
  6. }
  7. }

java Http post请求发送json字符串的更多相关文章

  1. wemall app商城源码中基于JAVA通过Http请求获取json字符串的代码

    wemall-mobile是基于WeMall的Android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.分享其中关于通过Http请求获取json字符串的代码供 ...

  2. ajax post 请求发送 json 字符串

    $.ajax({ // 请求方式 type:"post", // contentType contentType:"application/json", // ...

  3. java模拟post请求发送json

    java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: package main ...

  4. java模拟post请求发送json数据

    import com.alibaba.fastjson.JSONObject; import org.apache.http.client.methods.CloseableHttpResponse; ...

  5. httpclient工具类,post请求发送json字符串参数,中文乱码处理

    在使用httpclient发送post请求的时候,接收端中文乱码问题解决. 正文: 我们都知道,一般情况下使用post请求是不会出现中文乱码的.可是在使用httpclient发送post请求报文含中文 ...

  6. Java实现JSONObject对象与Json字符串互相转换

    Java实现JSONObject对象与Json字符串互相转换 JSONObject 转 JSON 字符串 Java代码: JSONObject jsonObject = new JSONObject( ...

  7. PHP如何通过Http Post请求发送Json对象数据?

    因项目的需要,PHP调用第三方 Java/.Net 写好的 Restful Api,其中有些接口,需要 在发送 POST 请求时,传入对象. Http中传输对象,最好的表现形式莫过于JSON字符串了, ...

  8. springboot使用RestTemplate以post方式发送json字符串参数(以向钉钉机器人发送消息为例)

    使用springboot之前,我们发送http消息是这么实现的 我们用了一个过时的类,虽然感觉有些不爽,但是出于一些原因,一直也没有做处理,最近公司项目框架改为了springboot,springbo ...

  9. Java 对象,数组 与 JSON 字符串 相互转化

    当 Java 对象中包含 数组集合对象时,将 JSON 字符串转成此对象. public class Cart{} public class MemberCoupon{} public class C ...

随机推荐

  1. 什么是Etcd?

    文章大部分引至:http://jolestar.com/etcd-architecture/ Etcd 按照官方介绍 Etcd is a distributed, consistent key-val ...

  2. 什么是Kubernetes?

    刚刚进学校实验室,第一次开会导师和小组同学说了n次Kubernetes,从来没听过,一脸懵逼. Kubernetes也有很多人把它叫K8S, 原文链接:http://omerio.com/2015/1 ...

  3. apache kafka系列之server.properties配置文件参数说明

    每个kafka broker中配置文件server.properties默认必须配置的属性如下: broker.id=0num.network.threads=2num.io.threads=8soc ...

  4. Poj3253:Fence Repair 【贪心 堆】

    题目大意:背景大概是个资本家剥削工人剩余价值的故事....有一块木板,要把它切成几个长度,切一次的费用是这整块被切木板的长度,例如将一个长度为21的木板切成2和19两块费用为21,切成两块的长度及顺序 ...

  5. 2016 Multi-University Training Contest 8 solutions BY 学军中学

    1001: 假设有4个红球,初始时从左到右标为1,2,3,4.那么肯定存在一种方案,使得最后结束时红球的顺序没有改变,也是1,2,3,4. 那么就可以把同色球都写成若干个不同色球了.所以现在共有n个颜 ...

  6. 简述WEB项目前端脚本的一次重构历程,labJs,requireJs实践[转载]

    重构前的状态:    大量的js代码混在繁多的Jsp文件中,对第三方的js库依赖也很杂乱.虽然在部分交互性较强的页面中,将js代码分离到了独立的js文件中,但是代码结构及依赖管理依然很乱.不说新人来了 ...

  7. Delphi字符串加密/解密

    unit uEncrypt_Decrypt;   interface   uses SysUtils;   const XorKey: array[0..7] of Byte = ($B2, $09, ...

  8. 【小记事】解除端口占用(Windows)

    开发中有时会因为端口占用而导致起项目时报错(如下图),这时候只要解除端口占用即可. 解除端口占用: 1.打开cmd(win+r),查看端口占用情况 netstat -ano | findstr 端口号 ...

  9. 转:浅谈Linux的内存管理机制

    一 物理内存和虚拟内存          我们知道,直接从物理内存读写数据要比从硬盘读写数据要快的多,因此,我们希望所有数据的读取和写入都在内存完成,而内存是有限的,这样就引出了物理内存与虚拟内存的概 ...

  10. 【.Net 学习系列】-- Windows身份模拟(WindowsIdentity.Impersonate)时读取Access数据库

    参考资料: WindowsIdentity.Impersonate https://msdn.microsoft.com/zh-cn/library/w070t6ka(v=vs.110).aspx A ...