package com.elink.estos.mq.mqmanager;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class JavaPostJson2 {
    final static String url = "http://localhost:1111/sendData";
    final static String params = "{\"token\":\"12345\","
            + "\"appId\":\"20180628173051169c85d965d164ed9ab1281d22ff350ec19\"" + "\"appName\":\"test33\""
            + "\"classTopic\":\"112\"" + "\"eventTag\":\"22\"" + "}";

    public static void main(String[] args) {

        String res = post(url, params);
        System.out.println(res);

    }

    /**
     * 发送HttpPost请求
     *
     * @param strURL
     *            服务地址
     * @param params
     *            json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/>
     * @return 成功:返回json字符串<br/>
     */
    public static String post(String strURL, String params) {
        System.out.println(strURL);
        System.out.println(params);
        BufferedReader reader = null;
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            // connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            //一定要用BufferedReader 来接收响应, 使用字节来接收响应的方法是接收不到内容的
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            out.flush();
            out.close();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            reader.close();

            //如果一定要使用如下方式接收响应数据, 则响应必须为: response.getWriter().print(StringUtils.join("{\"errCode\":\"1\",\"errMsg\":\"", message, "\"}")); 来返回
//            int length = (int) connection.getContentLength();// 获取长度
//            if (length != -1) {
//                byte[] data = new byte[length];
//                byte[] temp = new byte[512];
//                int readLen = 0;
//                int destPos = 0;
//                while ((readLen = is.read(temp)) > 0) {
//                    System.arraycopy(temp, 0, data, destPos, readLen);
//                    destPos += readLen;
//                }
//                String result = new String(data, "UTF-8"); // utf-8编码
//                System.out.println(result);
//                return result;
//            }

            return res;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }

}

import java.io.IOException;import java.io.InputStream;import java.io.OutputStreamWriter;import java.net.HttpURLConnection;import java.net.URL;import java.io.BufferedReader;import java.io.InputStreamReader;
public class JavaPostJson2 {final static String url = "http://localhost:1111/sendData";// final static String params = "{\"token\":\"12345\","// + "\"appId\":\"20180628173051169c85d965d164ed9ab1281d22ff350ec19\"" // + "\"appName\":\"test33\""// + "\"classTopic\":\"112\"" // + "\"eventTag\":\"22\"" // + "\"msg\":{}"// + "}";final static String params = "{\"token\":\"12345\","+ "\"appId\":\"20180628173051169c85d965d164ed9ab1281d22ff350ec19\","+ "\"appName\":\"test33\","+ "\"classTopic\":\"112\","+ "\"eventTag\":\"22\""+ "}";
public static void main(String[] args) {
String res = post(url, params);System.out.println(res);
}
/** * 发送HttpPost请求 *  * @param strURL *            服务地址 * @param params *            json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/> * @return 成功:返回json字符串<br/> */public static String post(String strURL, String params) {System.out.println(strURL);System.out.println(params);BufferedReader reader = null;try {URL url = new URL(strURL);// 创建连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setDoInput(true);connection.setUseCaches(false);connection.setInstanceFollowRedirects(true);connection.setRequestMethod("POST"); // 设置请求方式// connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式connection.connect();OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码out.append(params);out.flush();out.close();// 读取响应reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));String line;String res = "";while ((line = reader.readLine()) != null) {res += line;}reader.close();
return res;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "error"; // 自定义错误信息}
}

java发送post 的json请求的更多相关文章

  1. JAVA发送http get/post请求,调用http接口、方法

    import java.io.BufferedReader; import java.io.IOException;import java.io.InputStream; import java.io ...

  2. Java发送http get/post请求,调用接口/方法

    由于项目中要用,所以找了一些资料,整理下来. GitHub地址: https://github.com/iamyong    转自:http://blog.csdn.net/capmiachael/a ...

  3. JAVA发送http GET/POST请求的两种方式+JAVA http 请求手动配置代理

    java发送http get请求,有两种方式. 第一种用URLConnection: public static String get(String url) throws IOException { ...

  4. Java 发送Get和Post请求

    package com.htpt.superviseServices.dm.util; import java.io.BufferedReader; import java.io.IOExceptio ...

  5. Java 发送http GET/POST请求

    最近项目里面需要用到Java发送http请求,由于发送https请求有点复杂,暂时不考虑 HttpURLConnection HttpURLConnection是一种多用途.轻量极的HTTP客户端,使 ...

  6. Java发送get及post请求工具方法

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...

  7. [java,2018-01-16] HttpClient发送、接收 json 请求

    最近需要用到许多在后台发送http请求的功能,可能需要发送json和xml类型的数据. 就抽取出来写了一个帮助类: 首先判断发送的数据类型是json还是xml: import org.dom4j.Do ...

  8. java发送GET和post请求

    package com.baqingshe.bjs.util; import java.io.BufferedReader; import java.io.IOException; import ja ...

  9. 【工具】java发送GET、POST请求

    前项目使用这种HTTP的方式进行数据交互,目前已更换数据交互方式,但是作为接口提供调用来说还是比较简洁高效的: 总体流程就是: 1.发送HTTP请求 2.获取返回的JSON对象 3.JSON转换 pa ...

随机推荐

  1. 用python写定时任务

    一个是sched模块,一个是threading模块 参考链接:http://www.cnblogs.com/LinTeX9527/p/6181523.html

  2. 恢复所有情况的ip地址

    在终端下输入一串ip字符串如:19219219211,ip地址可能是19.219.219.211.192.19.219.211.192.192.19.211和192.192.192.11. 以下是本人 ...

  3. fn project 生产环境使用

    此为官方的参考说明   Running Fn in Production The QuickStart guide is intended to quickly get started and kic ...

  4. Nginx httpS server配置

    Nginx httpS 配置 配置同时支持http和httpS协议: server { listen ; #backlog:每个网络接口接收数据包的速率比内核处理这些包的速率快时,允许送到队列的数据包 ...

  5. DHCP(三)

    选择阶段:即DHCP客户端选择IP地址的阶段.如果有多台DHCP服务器向该客户端发来DHCP Offer报文,客户端只接受第一个收到的DHCP Offer报文,然后以广播方式发送DHCP Reques ...

  6. distinct与order by

    不知为啥,当我得查询中出现distinct时,order by 中必须包含要查询的列,否则报错. SELECT DISTINCT a.DetailId, a.OrderId, a.ProductId, ...

  7. (转)Oracle存储过程基本语法

    本文转载自:http://www.cnblogs.com/hero4china/articles/base_rule_oracle_procedure.html 存储过程 1  CREATE OR R ...

  8. java图形用户界面添加背景颜色不成功的解决方案

    总结:背景颜色不成功,那么使用这个方法试试.getContentpane(); package clientFrame; import java.awt.Color; import java.awt. ...

  9. 杂项:WiKi

    ylbtech-杂项:WiKi Wiki是一种在网络上开放且可供多人协同创作的超文本系统,由沃德·坎宁安于1995年首先开发,这种超文本系统支持面向社群的协作式写作,同时也包括一组支持这种写作.沃德· ...

  10. php爬虫神器cURL

    cURL 网页资源(编写网页爬虫) 接口资源 ftp服务器文件资源 其他资源 static public function curl($url, $data = array(), $timeout = ...