• JAVA HTTP POST参数为一个对象或数组


    原文链接http://zhaochao.net/index.php/2015/12/04/4/

    问题描述

    最近接到一个很简单的问题,对方提供了一个接口,让我每隔一段时间像他的接口推送一些数据,因为数据量比较大,所以这种Http 请求类型肯定是Post请求。这种推送过去的参数是一个很大的数组,而且数据字段比较多,所以用key=value 这种形式传过去就不太适合了,应该直接将这种数组加入Http的body体中,一次性传过去,接收放也不需要一个一个字段解析,全部取出body体中数据,再解析就可以了。
    假设传递参数为

    [
        {
            "name": "赵云",
            "age": "20"
        },
        {
            "name": "马超",
            "age": "30"
        }
    ]

    服务端实现

    新建一个serlvet3.0 处理Post 请求

    @WebServlet("/hello")
    public class Hello extends HttpServlet {
        private static final long serialVersionUID = 1L;  
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            BufferedReader br=new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            String line="";
            String res="";
            while(null!=(line=br.readLine())){
                res+=line;
            }
            JSONArray array=JSONArray.parseArray(res);
            for(int i=0;i<array.size();i++){
                JSONObject user=array.getJSONObject(i);
                System.out.println(String.format("name=%s age=%s",user.getString("name"),user.getString("age")));
            }
            response.setCharacterEncoding("utf-8");
            response.getWriter().append("Served at: ").append(res);
    
        }
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

    客户端调用实现

    public class Main { 
        public static final String ADD_URL = "http://localhost:8080/PostDemo/hello"; 
        public static void main(String[] args) { 
             try { 
                 //创建连接 
                 URL url = new URL(ADD_URL); 
                 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
                 connection.setDoOutput(true); 
                 connection.setDoInput(true); 
                 connection.setRequestMethod("POST"); 
                 connection.setUseCaches(false); 
                 connection.setInstanceFollowRedirects(true); 
                 connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
                 connection.connect(); 
                 //POST请求 
                 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 
                 JSONObject user = new JSONObject(); 
                 user.put("name", "赵云"); 
                 user.put("age", "20");
                 JSONObject user2 = new JSONObject(); 
                 user2.put("name","马超"); 
                 user2.put("age", "30");
                 JSONArray userArray=new JSONArray();
                 userArray.add(user);
                 userArray.add(user2);
                 out.write(userArray.toString().getBytes("UTF-8"));
                 out.flush(); 
                 out.close(); 
                 //读取响应 
                 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
                 String lines; 
                 StringBuffer sb = new StringBuffer(""); 
                 while ((lines = reader.readLine()) != null) { 
                     lines = new String(lines.getBytes(), "utf-8"); 
                     sb.append(lines); 
                 } 
                 System.out.println(sb); 
                 reader.close(); 
                 // 断开连接 
                 connection.disconnect(); 
             } catch (MalformedURLException e) { 
                 // TODO Auto-generated catch block 
                 e.printStackTrace(); 
             } catch (UnsupportedEncodingException e) { 
                 // TODO Auto-generated catch block 
                 e.printStackTrace(); 
             } catch (IOException e) { 
                 // TODO Auto-generated catch block 
                 e.printStackTrace(); 
             } 
        } 
    } 

    测试结果

    服务端输出结果
    服务端结果
    客户端输出结果
    这里写图片描述

  • 相关阅读:
    ETCD集群部署 和flanne网络插件通信原理介绍
    prometheus02 nodeexporter部署及使用
    docker容器的存储资源(volume)
    ActionScript 3.0 事件机制小结
    ActionScript 3.0 装饰器模式实例
    固定头和底,中间部分自适应布局
    ActionScript 3.0 MVC模式小实例
    A*算法的Actionscript3.0实例
    [Database]sql server 2008 不允许保存更改,您所做的更改要求删除并重新创建以下表 的解决办法
    在phpstorm中svn的使用
  • 原文地址:https://www.cnblogs.com/whzhaochao/p/5023399.html
Copyright © 2020-2023  润新知