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 = ...
随机推荐
- Msql:Incorrect double value: ''for column 'id' at row 1解决
Incorrect double value: ''for column 'id' at row 1解决 最近在写个查询 插入语句的时候 我是这么写的 1 insert into test val ...
- Android Activity 四种启动模式
task和back stack(任务和回退栈) 任务启动,task被加入到回退栈的栈顶,返回的时候回退栈的栈顶任务会被弹出,并被销毁,栈中的前一任务恢复运行,当activity销毁是,系统不会保留ac ...
- java 在linux环境下写入 syslog 问题研究
1.Syslog 在Unix类操作系统上,syslog广泛应用于系统日志.syslog日志消息既可以记录在本地文件中,也可以通过网络发送到接收syslog的服务器.接收syslog的服务器可以对多个设 ...
- jquery实现静态html文件的include嵌入效果
//引入jQuery的js 建立footer.html,内容为要嵌入的内容. 在需要嵌入的页面中加入: $.get("footer.html",function(data){ $( ...
- PHP大文件存储示例,各种文件分割和合并(二进制分割与合并)
最近要对视频进行上传,由于涉及到的视频非常的大,因此采用的是分片上传的格式,下面是一个简单的例子: split.php <?php $i = 0; //分割的块编号 $fp = fopen(&q ...
- php:微信公众号token验证失败原因、验证码显示不出来的问题
ob_clean(); 问题描述: 用微信官方提供的demo验证token是成功的,但是放到自己网站的框架上进行token验证老是提示"token验证失败",经过检查(用生成日志的 ...
- Winform 窗体控件随窗体自动(等比例)调整大小
新建窗体程序了,添加窗体事件Load(加载窗体时).Resize(调整控件大小时).自定义方法setTag(获取控件的width.height.left.top.字体大小等信息的值).setContr ...
- mysql 用source 导入数据库报错
平时一直使用phpmyadmin或mysqldum进行导出,使用source命令导入数据库. 但换了新版本mysql后,上述导入方法出现以下错误: ERROR: Unknown command '\\ ...
- 关于 矩阵在ACM中的应用
关于矩阵在ACM中的应用 1.矩阵运算法则 重点说说矩阵与矩阵的乘法,不说加减法. 支持: 结合律 (AB)C = A(BC) 分配律 A(B+C) = AB + AB $\left( \lambd ...
- 跨过几个坑,终于完成了我的第一个Xamarin Android App!
时间过得真快,距离上次发随笔又是一年多.作为上次发的我的第一个WP8.1应用总结的后继,这次同样的主要功能,改为实现安卓版APP.前几个月巨硬收购Xamarin,把Xamarin集成到VS里了,大大方 ...