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. asp.net MVC上传图片完整方法

    图片上传 自动创建文件夹并重命名(带缩略图) 后台: [HttpPost] public ActionResult WanSell_UploadPicture(ProductGalleryModels ...

  2. mysql卸载(转)

    按以下步骤卸载mysql server 主要步骤: 1. 停止服务MySQL 2. 卸载mysql相关的程序 3. 删除注册表(运行->regedit),machine->system-& ...

  3. python-etcd

    Client 对象 ['_MDELETE', '_MGET', '_MPOST', '_MPUT', '__class__', '__contains__', '__del__', '__delatt ...

  4. 软件工程练习, 模块化,单元测试,回归测试,TDD

    这是<构建之法>实战教学的一部分.适合作为同学们的第二个程序作业. 第一个程序作业: 请看 “概论” 一章的练习,或者老师的题目,例如这个. 作业要求: 软件工程的作业越来越有意思了, 我 ...

  5. C# 设计模式之工厂模式(一)

    写在前面,PS一句:笔记专用,轻拍勿喷,看的不爽绕路前行即可. 一.举栗说明 1.剧情:某银行财务有三位员工,分别为A.B.C三人,主要任务就是去银行取钱,如下: class EmloyeeA: { ...

  6. SQL Server 的数据库简单操作

    --创建数据库--create database 数据库名称[on [primary](name='主数据逻辑文件名',filename='完整的路径.文件名和拓展名'[,size=文件大小][,fi ...

  7. 重走java---Step 1

    开发环境 1.使用java开发,首先要完成java运行环境的安装配置,JVM可以说是java最大的优点之一,就是它实现了java一次编译多次运行,关于JVM以后再详谈.安装配置JDK,完成java开发 ...

  8. SQL Server执行计划的理解

    详细看:http://www.cnblogs.com/kissdodog/p/3160560.html 自己总结: 扫描Scan:逐行遍历数据. 查找Seek:根据查询条件,定位到索引的局部位置,然后 ...

  9. json与对象转化

    /// <summary> /// 把JSON字符串还原为对象 /// </summary> /// <typeparam name="T">对 ...

  10. 给员工授予svn相关权限

    步骤: 了解:地址2.4是代码svn.地址2.16是文档svn 以授予 SVN地址是:http://172.16.2.16/svn/SystemNetworkBU  权限组为mam_group,是只读 ...