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

public class HttpClientHelper {private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).setConnectionRequestTimeout(15000).build();private static HttpClientHelper instance = null;public HttpClientHelper() {}public static HttpClientHelper getInstance() {if (instance == null) {instance = new HttpClientHelper();}return instance;}/*** 发送 post请求** @param httpUrl*            地址*/public String sendHttpPost(String httpUrl) {HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPostreturn sendHttpPost(httpPost);}/*** 发送 post请求** @param httpUrl*            地址* @param params*            参数(格式:key1=value1&key2=value2)*/public String sendHttpPost(String httpUrl, String params) {HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPosttry {// 设置参数StringEntity stringEntity = new StringEntity(params, "UTF-8");stringEntity.setContentType("application/x-www-form-urlencoded");httpPost.setEntity(stringEntity);} catch (Exception e) {e.printStackTrace();}return sendHttpPost(httpPost);}/*** 发送 post请求** @param httpUrl*            地址* @param maps*            参数*/public String sendHttpPost(String httpUrl, Map<String, String> maps) {HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost// 创建参数队列List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();for (String key : maps.keySet()) {nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));}try {httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));} catch (Exception e) {e.printStackTrace();}return sendHttpPost(httpPost);}/*** 发送 post请求(带文件)** @param httpUrl*            地址* @param maps*            参数* @param fileLists*            附件*/public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPostMultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();if (maps != null) {for (String key : maps.keySet()) {meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));}}if (fileLists != null) {for (File file : fileLists) {FileBody fileBody = new FileBody(file);meBuilder.addPart("files", fileBody);}}HttpEntity reqEntity = meBuilder.build();httpPost.setEntity(reqEntity);return sendHttpPost(httpPost);}/*** 发送Post请求** @param httpPost* @return*/private String sendHttpPost(HttpPost httpPost) {CloseableHttpClient httpClient = null;CloseableHttpResponse response = null;HttpEntity entity = null;String responseContent = null;try {// 创建默认的httpClient实例.httpClient = HttpClients.createDefault();httpPost.setConfig(requestConfig);// 执行请求response = httpClient.execute(httpPost);entity = response.getEntity();responseContent = EntityUtils.toString(entity, "UTF-8");} catch (Exception e) {e.printStackTrace();} finally {try {// 关闭连接,释放资源if (response != null) {response.close();}if (httpClient != null) {httpClient.close();}} catch (IOException e) {e.printStackTrace();}}return responseContent;}public String sendJsonHttpPost(String url, String json) {CloseableHttpClient httpclient = HttpClients.createDefault();String responseInfo = null;try {HttpPost httpPost = new HttpPost(url);httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");ContentType contentType = ContentType.create("application/json", CharsetUtils.get("UTF-8"));httpPost.setEntity(new StringEntity(json, contentType));CloseableHttpResponse response = httpclient.execute(httpPost);HttpEntity entity = response.getEntity();int status = response.getStatusLine().getStatusCode();if (status >= 200 && status < 300) {if (null != entity) {responseInfo = EntityUtils.toString(entity);}}} catch (Exception e) {e.printStackTrace();} finally {try {httpclient.close();} catch (IOException e) {e.printStackTrace();}}return responseInfo;}/*** 发送 get请求** @param httpUrl*/public String sendHttpGet(String httpUrl) {HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求return sendHttpGet(httpGet);}/*** 发送 get请求Https** @param httpUrl*/public String sendHttpsGet(String httpUrl) {HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求return sendHttpsGet(httpGet);}/*** 发送Get请求** @param httpGet* @return*/private String sendHttpGet(HttpGet httpGet) {CloseableHttpClient httpClient = null;CloseableHttpResponse response = null;HttpEntity entity = null;String responseContent = null;try {// 创建默认的httpClient实例.httpClient = HttpClients.createDefault();httpGet.setConfig(requestConfig);// 执行请求response = httpClient.execute(httpGet);entity = response.getEntity();responseContent = EntityUtils.toString(entity, "UTF-8");} catch (Exception e) {e.printStackTrace();} finally {try {// 关闭连接,释放资源if (response != null) {response.close();}if (httpClient != null) {httpClient.close();}} catch (IOException e) {e.printStackTrace();}}return responseContent;}/*** 发送Get请求Https** @param httpGet* @return*/private String sendHttpsGet(HttpGet httpGet) {CloseableHttpClient httpClient = null;CloseableHttpResponse response = null;HttpEntity entity = null;String responseContent = null;try {// 创建默认的httpClient实例.PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();httpGet.setConfig(requestConfig);// 执行请求response = httpClient.execute(httpGet);entity = response.getEntity();responseContent = EntityUtils.toString(entity, "UTF-8");} catch (Exception e) {e.printStackTrace();} finally {try {// 关闭连接,释放资源if (response != null) {response.close();}if (httpClient != null) {httpClient.close();}} catch (IOException e) {e.printStackTrace();}}return responseContent;}public static void main(String[] args) {HttpClientHelper h = new HttpClientHelper();Map map = new HashMap();map.put("messageid", "test00201612210002");map.put("clientid", "test00");map.put("index_id", "买方会员");map.put("threshold", 0.9);List<String> data = new ArrayList<String>();data.add("wo xiang cha xun jin tian de yao pin jia ge lie biao");map.put("data", data);String json = JSON.toJSONString(map);String reply = h.sendJsonHttpPost("http://11.11.40.63:7777/algor/simclassify", json);System.out.println("reply->"+reply);}
}

java里遍历动态key:

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

转载于:https://www.cnblogs.com/cosyer/p/6295746.html

java Http post请求发送json字符串相关推荐

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

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

  2. java curl json_POST请求发送json数据java HttpUrlConnection

    我开发了一个java代码,使用URL和HttpUrlConnection将以下cURL转换为java代码.卷曲是: curl -i 'http://url.com' -X POST -H " ...

  3. java post json请求_java模拟post请求发送json

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

  4. java给第三方接口发送数据_对接第三方接口--使用post请求发送json数据

    对接第三方接口–使用post请求发送json数据 实习4个多月,终于转正!终于可以安心好好上班,好好学习!第一篇播客记录下工作中的中的小知识点. 本文记录的内容如下: 1.使用HttpClient相关 ...

  5. Java以post请求发送文件或json数据

    分别给出了post发送文件和json数据的函数,其中使用到了Jackson库来转化Json数据,使用log4j2来打印日记,可自行剔除. public class HttpUtils {static ...

  6. php7 mysql json 小程序_微信小程序php传递post请求发送json数据以获取小程序码

    困扰了两天的问题终于解决了! 用php传递post请求,发送json数据到微信小程序提供的接口,以此获得微信小程序码,下面是代码展示:<?php //需要传递的json数据 //能传递的参数,详 ...

  7. Java系列之:生成Json字符串

    Java系列之:生成Json字符串 一.拼接Json字符串 二.使用JSONObject()生成字符串 一.拼接Json字符串 import com.alibaba.fastjson.JSONObje ...

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

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

  9. ajax返回字符串怎么处理,ajax请求返回json字符串/json对象 处理

    1. 返回json字符串如何处理 $.ajax({ url:xxx, success:function(date){ }, error:function(){ } }); 通过最原始的返回: Prin ...

  10. php curl json post请求_php post请求发送json对象数据参数

    网页中发送请求时,大部分情况都参数以键值组合发送数据的,而一些第三方如java开发的接口中需要发送post请求,请求参数为json类型. 既然要发送json数据,首页我们需要在请求头中定义数据类型为j ...

最新文章

  1. idea缩写快捷键_IDEA快捷键大全 快速页面重构
  2. pandas使用replace函数和正则表达式移除dataframe字符串数据列中尾部指定模式字符串(Removing trailing substring in dataframe)
  3. 阿里技术协会(ATA)11月系列精选文集
  4. web.config总结
  5. substring()分解字符串
  6. IDEA中 @override报错的解决方法
  7. 通用窗口类 Inventory Pro 2.1.2 Demo1(中)
  8. JavaScript 调用 Web Service 的多种方法
  9. 问题解决逻辑:深度和广度谁应该优先?
  10. Unity人物残影实现
  11. rsync简介及部署
  12. 移动端 --- 解决苹果手机滑动卡顿的问题
  13. 免费合并多个PDF文件
  14. 数学计算机软件课程,《数学软件》课程教学大纲.doc
  15. 看雪3万课程笔记-FRIDA高级API实用方法:Frida Hook Java(一)
  16. 人的顶级能量从哪里获取?
  17. mybatis大于号 小于号
  18. 软件工程导论张海蕃书籍pdf_软件工程导论张海蕃 课后习题答案
  19. 航天科工研发“高速飞行列车”,最高时速可达4000公里?
  20. 推荐系统学习笔记03-矩阵分解和FM

热门文章

  1. NOI题库--砝码称重V2(多重背包2^n拆分)
  2. VS2008+QT+CYAPI开发USB程序问题
  3. Arturia Analog Lab V for Mac - 超强键盘模拟合成器
  4. mac电脑更新后,如何解决mac在文件夹中无权限新建文件?
  5. 如何使用Mac预览程序将png转换为jpg格式的技巧分享
  6. Tuxera Ntfs for mac内核扩展批准不了怎么办 手动批准mac内核扩展
  7. U盘插入电脑无反应,坏了?不存在的
  8. 使用DataTables合并行
  9. 第一次scrum冲刺!
  10. 高德正式开放海外LBS服务,助力开发者出海