java Http post请求发送json字符串
最近差点被业务逻辑搞懵逼,果然要先花时间思考,确定好流程再执行。目前最好用的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);// 创建httpPost
- return sendHttpPost(httpPost);
- }
- /**
- * 发送 post请求
- *
- * @param httpUrl
- * 地址
- * @param params
- * 参数(格式:key1=value1&key2=value2)
- */
- public String sendHttpPost(String httpUrl, String params) {
- HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
- try {
- // 设置参数
- 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);// 创建httpPost
- MultipartEntityBuilder 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();
- }
- }
java Http post请求发送json字符串的更多相关文章
- wemall app商城源码中基于JAVA通过Http请求获取json字符串的代码
wemall-mobile是基于WeMall的Android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.分享其中关于通过Http请求获取json字符串的代码供 ...
- ajax post 请求发送 json 字符串
$.ajax({ // 请求方式 type:"post", // contentType contentType:"application/json", // ...
- java模拟post请求发送json
java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求, 方法一: package main ...
- java模拟post请求发送json数据
import com.alibaba.fastjson.JSONObject; import org.apache.http.client.methods.CloseableHttpResponse; ...
- httpclient工具类,post请求发送json字符串参数,中文乱码处理
在使用httpclient发送post请求的时候,接收端中文乱码问题解决. 正文: 我们都知道,一般情况下使用post请求是不会出现中文乱码的.可是在使用httpclient发送post请求报文含中文 ...
- Java实现JSONObject对象与Json字符串互相转换
Java实现JSONObject对象与Json字符串互相转换 JSONObject 转 JSON 字符串 Java代码: JSONObject jsonObject = new JSONObject( ...
- PHP如何通过Http Post请求发送Json对象数据?
因项目的需要,PHP调用第三方 Java/.Net 写好的 Restful Api,其中有些接口,需要 在发送 POST 请求时,传入对象. Http中传输对象,最好的表现形式莫过于JSON字符串了, ...
- springboot使用RestTemplate以post方式发送json字符串参数(以向钉钉机器人发送消息为例)
使用springboot之前,我们发送http消息是这么实现的 我们用了一个过时的类,虽然感觉有些不爽,但是出于一些原因,一直也没有做处理,最近公司项目框架改为了springboot,springbo ...
- Java 对象,数组 与 JSON 字符串 相互转化
当 Java 对象中包含 数组集合对象时,将 JSON 字符串转成此对象. public class Cart{} public class MemberCoupon{} public class C ...
随机推荐
- 什么是Etcd?
文章大部分引至:http://jolestar.com/etcd-architecture/ Etcd 按照官方介绍 Etcd is a distributed, consistent key-val ...
- 什么是Kubernetes?
刚刚进学校实验室,第一次开会导师和小组同学说了n次Kubernetes,从来没听过,一脸懵逼. Kubernetes也有很多人把它叫K8S, 原文链接:http://omerio.com/2015/1 ...
- apache kafka系列之server.properties配置文件参数说明
每个kafka broker中配置文件server.properties默认必须配置的属性如下: broker.id=0num.network.threads=2num.io.threads=8soc ...
- Poj3253:Fence Repair 【贪心 堆】
题目大意:背景大概是个资本家剥削工人剩余价值的故事....有一块木板,要把它切成几个长度,切一次的费用是这整块被切木板的长度,例如将一个长度为21的木板切成2和19两块费用为21,切成两块的长度及顺序 ...
- 2016 Multi-University Training Contest 8 solutions BY 学军中学
1001: 假设有4个红球,初始时从左到右标为1,2,3,4.那么肯定存在一种方案,使得最后结束时红球的顺序没有改变,也是1,2,3,4. 那么就可以把同色球都写成若干个不同色球了.所以现在共有n个颜 ...
- 简述WEB项目前端脚本的一次重构历程,labJs,requireJs实践[转载]
重构前的状态: 大量的js代码混在繁多的Jsp文件中,对第三方的js库依赖也很杂乱.虽然在部分交互性较强的页面中,将js代码分离到了独立的js文件中,但是代码结构及依赖管理依然很乱.不说新人来了 ...
- Delphi字符串加密/解密
unit uEncrypt_Decrypt; interface uses SysUtils; const XorKey: array[0..7] of Byte = ($B2, $09, ...
- 【小记事】解除端口占用(Windows)
开发中有时会因为端口占用而导致起项目时报错(如下图),这时候只要解除端口占用即可. 解除端口占用: 1.打开cmd(win+r),查看端口占用情况 netstat -ano | findstr 端口号 ...
- 转:浅谈Linux的内存管理机制
一 物理内存和虚拟内存 我们知道,直接从物理内存读写数据要比从硬盘读写数据要快的多,因此,我们希望所有数据的读取和写入都在内存完成,而内存是有限的,这样就引出了物理内存与虚拟内存的概 ...
- 【.Net 学习系列】-- Windows身份模拟(WindowsIdentity.Impersonate)时读取Access数据库
参考资料: WindowsIdentity.Impersonate https://msdn.microsoft.com/zh-cn/library/w070t6ka(v=vs.110).aspx A ...