zoukankan      html  css  js  c++  java
  • Java模拟POST请求发送二进制数据

    在进行程序之间数据通信时我们有时候就需要自定义二进制格式,然后通过HTTP进行二进制数据交互。交互的示例代码如下:

    public static void main(String[] args) {
        String result = "";
        try {
            String url = "http://localhost:8080/Demo/SiteApi";
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);        
            
            // 发送请求参数
            DataOutputStream dos=new DataOutputStream(conn.getOutputStream());
            String content="I love china";
            dos.write(content.getBytes());        
            
            // flush输出流的缓冲
            dos.flush();
            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println(result);//打印输出结果
        } catch (Exception e) {
            System.out.println("异常," + e.getMessage());
            e.printStackTrace();
        }
    }

    上面是模拟的http请求,如果是https请求,并且我们自己搭建的https可能证书不合法,因此需要在请求前加上下面的代码:

    javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier()  
    {        
        public boolean verify(String arg0, SSLSession arg1) {
            if (arg0.equals("119.84.112.220")) {
                return true;
            }
            return false;
        }  
    });

    上面的IP地址就是请求的ip地址。

    说一下重点吧:
    1.设置Content-Type的值必须为application/octet-stream,可参考http://tool.oschina.net/commons/
    2.发送二进制数据必须使用到DataOutputStream

  • 相关阅读:
    python学习笔记 async and await
    python学习笔记 异步asyncio
    python学习笔记 协程
    python学记笔记 2 异步IO
    python学习笔记 可变参数关键字参数**kw相关学习
    逆波兰表达式 栈表达式计算
    Codeforces 270E Flawed Flow 网络流问题
    Codeforces 219D Choosing Capital for Treeland 2次DP
    kuangbin 带你飞 概率期望
    函数式编程思想:以函数的方式思考,第3部分
  • 原文地址:https://www.cnblogs.com/duanjt/p/7842761.html
Copyright © 2011-2022 走看看