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 ...
随机推荐
- 关于自由拖拽完成的剪切区域(UI组件之图片剪切器)
var x, y,areaWidth,areaHeight; var down;//闪光的判断标准,很好 addEvent(canvas,'mousedown',function(e){ // con ...
- python之图形界面GUI开发 Tkinter 2014-4-7
1.导入Tkinter 可以使用以下三种方法(1)from Tkinter import *#导入Tkinter(2)import TkinterTkinter.methodA使用 Tkinter.m ...
- python3--产生偏移和元素:enumerate
之前,我们讨论过通过range来产生字符串中元素的偏移值.而不是那些偏移值处的元素.不过,在有些程序中.我们两者都需要,要用的元素以及值个元素的偏移值.从传统意义来讲,这是简单的for循环,他同时也持 ...
- The more, The Better(树形DP)
Problem Description ACboy很喜欢玩一种战略游戏,在一个地图上,有N座城堡,每座城堡都有一定的宝物,在每次游戏中ACboy允许攻克M个城堡并获得里面的宝物.但由于地理位置原因,有 ...
- 关于datetime,date,timestamp,year,time时间类型小结
关于datetime,date,timestamp,year,time时间类型 datetime占用8个字节 日期范围:”1000-01-01 00:00:00” 到”9999-12-31 23:59 ...
- redis安装【三】
目录介绍: 0.Windows下下载安装包: 下载地址: https://redis.io/ 1.上传到linux服务器 将文件上传到192.168.2.128主机的usr/local目录下: C:\ ...
- IE下IFrame引用跨域站点页面时,Session失效问题解决
问题场景:在一个应用(集团门户)的某个page中, 通过IFrame的方式嵌入另一个应用(集团实时监管系统)的某个页面. 当两个应用的domain 不一样时, 在被嵌入的页面中Session失效.(s ...
- Django学习之 - 基础部分
学习记录参考: 讲师博客:http://www.cnblogs.com/wupeiqi/articles/5433893.html 老男孩博客:http://oldboy.blog.51cto.com ...
- python学习之-- subprocess模块
subprocess 模块 功能:用来生成子进程,并可以通过管道连接它们的输入/输出/错误,以及获得它们的返回值.它用来代替多个旧模块和函数: os.system os.spawn* os.popen ...
- 牛客网 牛客网暑期ACM多校训练营(第三场)E KMP
链接:https://www.nowcoder.com/acm/contest/141/E 题目描述 Eddy likes to play with string which is a sequenc ...