Use Apache HttpClient to Post json data
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import com.alibaba.fastjson.JSONObject;
InputStream is = null;
ByteArrayOutputStream bout = null;
try {
URIBuilder uriBuilder = new URIBuilder(envTO.getSocketApiURL());
HttpPost httpPost = new HttpPost(uriBuilder.build());
//httpPost.setHeader("Accept", "application/json");//经测,该参数可有可无
httpPost.setHeader("Content-type", "application/json");//必须要制定该参数
HttpClient httpClient = HttpClientBuilder.create().build(); JSONObject json = new JSONObject();
json.put("channel", channel);
json.put("action", action);
json.put("data", dataParm==null?new JSONObject():dataParm);
StringEntity s = new StringEntity(json.toString(),HTTP.UTF_8);
//s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));//经测,该参数可有可无
httpPost.setEntity(s); HttpResponse httpResponse = httpClient.execute(httpPost);
is = httpResponse.getEntity().getContent();
byte[] data = new byte[1024];
int length = 0;
bout = new ByteArrayOutputStream();
while((length=is.read(data))!=-1){
bout.write(data,0,length);
}
String result = new String(bout.toByteArray(),"UTF-8");
logger.info("sendNotice2SocketServer(): result is "+result);
} catch (URISyntaxException e1) {
logger.error("getAllMembers4Lucky(): IOException e1", e1);
} catch (UnsupportedOperationException e) {
logger.error("getAllMembers4Lucky(): UnsupportedOperationException e", e);
} catch (IOException e) {
logger.error("getAllMembers4Lucky(): IOException e", e);
} finally{
if(bout!=null){
IOUtils.closeQuietly(bout);
}
if(is!=null){
IOUtils.closeQuietly(is);
}
}
后台可以用SpringMVC做一个restful的api(自行bing搜索如何构建一个restful API. PS:推荐一个异常简单的框架: Spark)
---------------------------------------------------------------
另外发现一个以上代码无法正确提交到node.js的服务(一直404-Bad request,不知是哪里的问题,求解)
于是找了另一个提交的方法:
public static String postJson2Socket(String url, String jsonString, boolean isGet, boolean isJson){
HttpURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
BufferedReader br = null;
try{
if (isGet) {
if (jsonString == null) {
conn = (HttpURLConnection) new URL(url).openConnection();
} else {
conn = (HttpURLConnection) new URL(url + "?" + jsonString).openConnection();
}
conn.setDoOutput(false);
conn.setConnectTimeout(20000);
conn.setReadTimeout(20000);
// conn.setUseCaches(true);
conn.setRequestProperty("Accept", "application/json,text/html");
conn.setRequestProperty("Content-Type", "application/json");
} else {
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoOutput(true);
conn.setReadTimeout(10000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", isJson ? "application/json" : "application/x-www-form-urlencoded");
os = conn.getOutputStream();
os.write(jsonString.getBytes("UTF-8"));
os.flush();
}
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
is.close();
conn.disconnect();
return sb.toString();
}
catch(Exception e){
logger.error(e);
return "";
}
finally{
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(br);
IOUtils.closeQuietly(is);
if(conn!=null){
conn.disconnect();
}
}
}
该方法是可以成功提交给nodejs的
Use Apache HttpClient to Post json data的更多相关文章
- 使用Apache HttpClient 4.x发送Json数据
Apache HttpClient是Apache提供的一个开源组件,使用HttpClient可以很方便地进行Http请求的调用.自4.1版本开始,HttpClient的API发生了较大的改变,很多方法 ...
- Apache HttpClient 5 使用详细教程
点赞再看,动力无限. 微信搜「程序猿阿朗 」. 本文 Github.com/niumoo/JavaNotes 和 未读代码博客 已经收录,有很多知识点和系列文章. 超文本传输协议(HTTP)可能是当今 ...
- Introducing DataFrames in Apache Spark for Large Scale Data Science(中英双语)
文章标题 Introducing DataFrames in Apache Spark for Large Scale Data Science 一个用于大规模数据科学的API——DataFrame ...
- RESTful Java client with Apache HttpClient / URL /Jersey client
JSON example with Jersey + Jackson Jersey client examples RESTful Java client with RESTEasy client f ...
- Apache HttpClient 读取响应乱码问题总结
Apache HttpClient 读取响应乱码问题总结 setCharacterEncoding Content-Type HttpClient 起因 最近公司产品线研发人员调整,集中兵力做战 ...
- apache httpclient 4 范例
下面是一个通过apache httpclient 4 实现http/https的普通访问和BasicAuth认证访问的例子.依赖的第三方库为: 下面是具体实现: package test; impor ...
- 在android 6.0(API 23)中,Google已经移除了移除了Apache HttpClient相关的类
推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,需要在eclipse下libs里添加org.apache.http.legacy.jar,androi ...
- directly receive json data from javascript in mvc
if you send json data to mvc,how can you receive them and parse them more simply? you can do it like ...
- 论httpclient上传带参数【commons-httpclient和apache httpclient区别】
需要做一个httpclient上传,然后啪啪啪网上找资料 1.首先以前系统中用到的了commons-httpclient上传,找了资料后一顿乱改,然后测试 PostMethod filePost = ...
随机推荐
- Android 5.0属性
//水波纹效果//v 指定控件 x屏幕的 x轴 y轴 endRadio 起始位置 水波半径Animator circularReveal = ViewAnimationUtils.createCirc ...
- vs签入签出--TFS进行源代码管理
工作项是项目管理的基本元素.工作项说明了要做什么事(例如任务),出了什么问题(例如Bug),除此之外,我们还需要将程序一行一行地写出来,TFS的源代码管理控制系统,就能帮助我们管理这一行行的代码,一个 ...
- VUE 入门笔记
前端的MVVM概念今年来也算是如火如荼,了解完 MVVM的概念,也该找个去尝试下 首先我先试了下 国内小而美的 VUE 试着照着文档敲出入门文件,内容都在注释里 <!doctype html&g ...
- Python 2.7_pandas连接MySQL数据处理_20161229
在我本地Mysql_local_db数据库建立了一个pandas数据表用来对pandas模块的学习 学习过程借鉴学习蓝鲸的网站分析笔记 1.创建表 CREATE TABLE pandastest( 城 ...
- Java入门记(四):容器关系的梳理(上)——Collection
目录 一.Collection及子类/接口容器继承关系 二.List 2.1 ArrayList 2.1.1 序列化的探讨 2.1.2 删除元素 2.1.3 调整大小 2.2 Vector和Stack ...
- background-position还可以这样用
文章同步至微信公众号:http://mp.weixin.qq.com/s?__biz=MzAxMzgwNDU3Mg==&mid=401626453&idx=1&sn=6af07 ...
- 01.Sencha ExtJS 6 - Generate Workspace and Application
生成workspace 下载gpl版本的ExtJs6 在https://www.sencha.com/legal/GPL/页面的右侧申请链接来下载,或者使用链接http ...
- DSP下的#program
2014年7月22日 最近调试使用TMS320C6713的片子调试SDRAM,中间经过很多波折,这里就不吐槽了. 想将数据或者代码放到SDRAM上一定要用到#pragma .查阅资料后,感觉百度文库的 ...
- 协同开发中SVN的使用建议
协同开发中SVN的使用建议 1. 注意个人账户密码安全 各员工需牢记各自的账户和密码,不得向他人透漏,严禁使用他人账户进行SVN各项操作(主要考虑每个SVN账号的使用者的权限范围问题).如有忘记,请 ...
- DB2 syntax error
Error infomation: An unexpected token "JOIN" was found following "". Expected t ...