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的更多相关文章

  1. 使用Apache HttpClient 4.x发送Json数据

    Apache HttpClient是Apache提供的一个开源组件,使用HttpClient可以很方便地进行Http请求的调用.自4.1版本开始,HttpClient的API发生了较大的改变,很多方法 ...

  2. Apache HttpClient 5 使用详细教程

    点赞再看,动力无限. 微信搜「程序猿阿朗 」. 本文 Github.com/niumoo/JavaNotes 和 未读代码博客 已经收录,有很多知识点和系列文章. 超文本传输协议(HTTP)可能是当今 ...

  3. Introducing DataFrames in Apache Spark for Large Scale Data Science(中英双语)

    文章标题 Introducing DataFrames in Apache Spark for Large Scale Data Science 一个用于大规模数据科学的API——DataFrame ...

  4. RESTful Java client with Apache HttpClient / URL /Jersey client

    JSON example with Jersey + Jackson Jersey client examples RESTful Java client with RESTEasy client f ...

  5. Apache HttpClient 读取响应乱码问题总结

    Apache HttpClient 读取响应乱码问题总结 setCharacterEncoding  Content-Type  HttpClient  起因 最近公司产品线研发人员调整,集中兵力做战 ...

  6. apache httpclient 4 范例

    下面是一个通过apache httpclient 4 实现http/https的普通访问和BasicAuth认证访问的例子.依赖的第三方库为: 下面是具体实现: package test; impor ...

  7. 在android 6.0(API 23)中,Google已经移除了移除了Apache HttpClient相关的类

    推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,需要在eclipse下libs里添加org.apache.http.legacy.jar,androi ...

  8. 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 ...

  9. 论httpclient上传带参数【commons-httpclient和apache httpclient区别】

    需要做一个httpclient上传,然后啪啪啪网上找资料 1.首先以前系统中用到的了commons-httpclient上传,找了资料后一顿乱改,然后测试 PostMethod filePost = ...

随机推荐

  1. sql 用union合并合并查询结果

    合并操作与连接相似,因为他们都是将两个表合并起来的另一个表的方法,然而他们的合并方法有本质的区别, 合并是两个表的相加,连接时时两个表的相乘: 01 在合并中两个表原列的数量与数据类型必须相同:在连接 ...

  2. HBase的伪分布式安装(原创)

    准备工作: 1)安装了伪分布式hadoop:参照http://blog.csdn.net/zolalad/article/details/11472207 2)修改已安装好的hadoop配置文件: a ...

  3. [HTML]安卓下<video>无法点击播放

    在<video>外面添加<div>并加上data-tap-disabled="true"属性即可

  4. egret.Tween、egret.Ease

    循环调用.只能设置boolean,不能设置循环次数. egret.Tween.).call(()=>{ console.log("循环调用"); }) 每次改变时,调用onC ...

  5. Apache 配置 WebSocket 协议

    本文使用 http proxy 方式 实现 apache 支持  WebSocket 请求(JK 使用的 ajp 协议不能支持websocket) 通过 apache 访问 后端 tomcat上的 w ...

  6. 创建Unicode格式的INI文件

    前段时间由于开发一个软件,需要调用别人的接口,虽然我的软件是Unicode编码,对方的模块也是Unicode编码,但是对方提供的接口却是Ansi接口,在非中文系统下,由于涉及到中文路径,导致Ansi和 ...

  7. mysql的配置文件my.cnf

    调整MySQL运行参数,修改/etc/my.cnf文件调整mysql运行参数重启MySQL后生效,在MySQL4版本以后,一部分内部变量可以在MySQL运行时设置,不过重启MySQL就失效了. mys ...

  8. 读Javascript高级程序设计第三版第六章面向对象设计--创建对象

    虽然Object构造函数或者对象字面量都可以用来创建单个对象,但是缺点非常明显:使用同一接口创建很多对象,会产生大量重复代码. 工厂模式  1 function CreatePerson(name,a ...

  9. 【转】解决IIS7该问.svc文件的错误问题

        解决IIS7.5中部署WCF时,访问.svc文件的404错误问题如果你直接在IIS 7中配置WCF,访问.svc文件时会出现404错误.解决方法,以管理员身份进入命令行模式,运行:" ...

  10. 团队编程——web应用之人事管理系统

    本次作业为团队作业,团队博客要求如下:1. 介绍团队情况:包括队长.成员.队名.成员照片.队训--.等:2. 介绍团队项目名称.总体任务,各成员任务等:3. 每个队做 一次需求调研(针对团队项目),要 ...