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学习系列(三)(字符串)

    Python学习系列(三)(字符串) Python学习系列(一)(基础入门) Python学习系列(二)(基础知识) 一个月没有更新博客了,最近工作上有点小忙,实在是没有坚持住,丢久又有感觉写的必要了 ...

  2. 基于ThinkPHP的开发笔记3-登录功能(转)

    1.前台登录用的form ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <for ...

  3. 遍历listmap 遍历map

    package excel; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import j ...

  4. win10笔记本用Fiddler对手机App抓包

    移动客户端项目有时需要针对手机app进行抓包,这时一般有两种办法:直接下个手机抓包工具的app,在手机上抓:pc机上装上抓包工具,pc和手机连接同一个无线,在pc机上抓.第一种比较简单,但抓包工具自然 ...

  5. 不让activity显示UI的办法

    直接把 //setContentView(R.layout.activity_welcome); 注释掉就是了

  6. TabControl控件用法图解

    1.首先创建一个MFC对话框框架,在对话框资源上从工具箱中添加上一个TabControl控件 2.根据需要修改一下属性,然后右击控件,为这个控件添加一个变量,将此控件跟一个CTabCtrl类变量绑定在 ...

  7. erlang使用心跳模式启动shell

    资料http://blog.yufeng.info/archives/2832 借鉴自从http://blog.csdn.net/mycwq/article/details/18306753 测试例子 ...

  8. maven help:system

    lifecycle:http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html bindings:ht ...

  9. 【原创】官方文档-hive 启动命令

    [一起学Hive]之十六-Hive的WEB页面接口-HWI Apache Hive 管网 hive metrics hive常用命令整理 Hive学习之HiveServer2服务端配置与启动 启动hi ...

  10. zabbix snmp 协议监控 dell iRDAC

    转摘:http://blog.csdn.net/wanglei_storage/article/details/52789921 http://blog.csdn.net/wanglei_storag ...