HttpURLConnection接口json传参

public  String addPerson(String addOnePicJson,String mode) {
     Long timeStamp=System.currentTimeMillis();
     String sign=deviceUUID+":"+userName+":"+passWord+":"+timeStamp;
        String signMd5=getMD5(sign);
        HttpURLConnection conn = null;
        OutputStreamWriter out = null;
        try {
            URL url = new URL(baseUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);            
            System.out.println("add"+addOnePicJson);
            String json = "{\"Name\":\"WBListInfoREQ\",\"UUID\":\""+deviceUUID
                    +"\",\"TimeStamp\":"+timeStamp+",\"Sign\":\""
            +signMd5+"\",\"Mode\":"+mode+",\"Action\":\"AddOnePic\",\"AddOnePic\":"+addOnePicJson+"}";
            
            conn.connect();            
            out = new OutputStreamWriter(conn.getOutputStream(),"utf-8");//解决传参时中文乱码
            out.write(json);
            out.flush();
            InputStream inStream = conn.getInputStream();
            String result = new String(readInputStream(inStream),"utf-8");
            System.out.println(result);            
        return result;

        } catch (Exception e) {
            e.printStackTrace();
            return "添加人员出错";
            
        }
    }

public   byte[] readInputStream(InputStream input) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = input.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        input.close();
        return data;
    }

你可能感兴趣的:(JAVA)