http协议发送接收JSON数据

JSON转换问题

      
            com.alibaba
            fastjson
            1.2.48
        

JSON > Java对象

String jsonuser = "{\"age\":9,\"name\":\"J\",\"password\":\"001122334455\"}";
User user1 =   JSONObject.parseObject(jsonuser,User.class);

java对象 > json

 String s = JSONObject.toJSONString(user);

参考: https://blog.csdn.net/u012985132/article/details/52782494
https://blog.csdn.net/chenyulancn/article/details/77838314
https://blog.csdn.net/caidi1988314/article/details/72916165

GET请求发送和接收JSON
get接收JSON:

@RequestMapping(value="/get")
    @ResponseBody
    public User getUser(@ModelAttribute("user") String json){
        System.out.println("get 接收到:  "+json);
        User user1 =   JSONObject.parseObject(json,User.class);
        System.out.println("get 接收到:  "+user1.toString());
        User user = new User();
        user.setName("ZHANGSAN------get");
        user.setPassword("get-----123456789");
        user.setAge(12);
        return user;
    }

get发送JSON:

public String getJson() throws UnsupportedEncodingException {
        String url =  "http://localhost:8090/"+get;
        Map reqmap = new HashMap();
        reqmap.put("name","GET_JSON");
        reqmap.put("age",23);
        reqmap.put("password","123456");
        JSONObject obj = new JSONObject(reqmap);
        String r = URLEncoder.encode(obj.toString(), "UTF-8");
        System.out.println("转换出来的玩意儿:  "+r);
        String reqUrl = url+"/?user=" + r;
        System.out.println("请求参数:" + reqUrl);
        HttpURLConnection conn = null;
        try {
            // 创建一个URL对象
            URL mURL = new URL(reqUrl);
            // 调用URL的openConnection()方法,获取HttpURLConnection对象
            conn = (HttpURLConnection) mURL.openConnection();
            conn.setRequestMethod("GET");// 设置请求方法为post
            conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容
            int responseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法
            if (responseCode == 200) {   //访问成功
                InputStream is = conn.getInputStream();
                String state = getStringFromInputStream(is);  //这个函数在最后面
                System.out.println(state);
                return state;
            } else {
                System.out.print("访问失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();// 关闭连接
            }
        }
        return "error";
    }

POST请求发送和接收JSON
POST接收JSON:

@RequestMapping(value="/post" ,method = RequestMethod.POST)
    @ResponseBody
    public User postUser(@RequestBody User  user1){
        System.out.println("post 接收到:  "+user1);
        User user = new User();
        user.setName("ZHANGSAN------post");
        user.setPassword("post----123456789");
        user.setAge(12);
        return user;
    }

POST发送JSON:

public String postJson() {
        String url = "http://localhost:8090/post";
        HttpURLConnection conn = null;
        try {
            // 创建一个URL对象
            URL mURL = new URL(url);
            // 调用URL的openConnection()方法,获取HttpURLConnection对象
            conn = (HttpURLConnection) mURL.openConnection();
            conn.setRequestMethod("POST");// 设置请求方法为post
           /* conn.setReadTimeout(5000);// 设置读取超时为5秒
            conn.setConnectTimeout(10000);// 设置连接网络超时为10秒*/
            conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容
            // 设置文件类型:
            conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            conn.setRequestProperty("accept","application/json");
            int len = 0;
            // post请求的参数
            byte[] buf = new byte[10240];

            User user = new User();
            user.setName("POST_JSON");
            user.setAge(12);
            user.setPassword("00990099");
            String data = JSONObject.toJSONString(user);

            // 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
            OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据
            out.write(data.getBytes());
            out.flush();
            out.close();

            int responseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法
            if (responseCode == 200) {
                InputStream is = conn.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            } else {
                System.out.print("访问失败"+responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();// 关闭连接
            }
        }
        return null;
    }

getStringFromInputStream(InputStream)

private  String getStringFromInputStream(InputStream is)  throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 模板代码 必须熟练
        byte[] buffer = new byte[1024];
        int len = -1;
        // 一定要写len=is.read(buffer)
        // 如果while((is.read(buffer))!=-1)则无法将数据写入buffer中
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        is.close();
        String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)
        os.close();
        return state;
    }

你可能感兴趣的:(java)