将 Http 请求返回的 json 格式数据转换为 Object

本文只贴出核心部分代码,与业务相关的代码没有放出来~

自己觉得 Spring boot 中这么实现不是最优的,贴出来待后期优化,也望有更优解的不吝赐教~

​
    public List getInfoFromRemote()
    {
        List accounts= new ArrayList<>();
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(POLICE_ACCOUNT_ADDRESS);
        post.addHeader(HTTP.CONTENT_TYPE, "application/json");
        try
        {
            int begin = 0;
            int total = 0;
            int length = 500;

            do
            {
                String jsonBody = formatJsonBody(RESOURCE, begin, length);
                StringEntity s = new StringEntity(jsonBody);
                s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                s.setContentType("text/json");
                post.setEntity(s);

                HttpResponse res = client.execute(post);
                if (res.getStatusLine().getStatusCode() == HttpStatus.OK.value())
                {
                    String result = convertHttpResponseBodyToString(res);

                    JSONObject json = JSONObject.parseObject(result);
                    total = Integer.parseInt(json.getString("total"));
                    String data = json.getString("data");
                    List policeInfoList = JSONObject.parseArray(data, PoliceInfo.class);
                }
                begin += length;
            }
            while(begin < total);
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
        return accounts;
    }

    private String convertHttpResponseBodyToString(HttpResponse httpResponse) throws Exception
    {
        HttpEntity entity = httpResponse.getEntity();
        InputStream inputStream = entity.getContent();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1)
        {
            out.write(buffer, 0, len);
        }
        out.flush();

        byte[] ss = out.toByteArray();
        return new String(ss, "utf-8");
    }

    private String formatJsonBody(String resource, int begin, int length)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("{\"resource\": " + resource + ",");
        sb.append("\"where\": {},");
        sb.append("\"from\": " + begin + ",");
        sb.append("\"length\": " + length + "}");
        return sb.toString();
    }

    private String convertTimestamp2Date(Long timestamp)
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long time = new Long(timestamp);
        String d = format.format(time);
        return d;
    }

​
private static boolean httpPostWithJson(Map params)
    {
        boolean isSuccess = false;

        HttpPost post = null;
        try
        {
            HttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());

            post = new HttpPost(URL);
            // 构造消息头
            post.setHeader("Content-type", "application/json; charset=utf-8");

            // 构建消息实体
            String formatString = "{\"content\":" + params.get("content") +  ",\"phoneNum\": " + params.get("phoneNum") + "}";
            StringEntity stringEntity = new StringEntity(formatString, "UTF-8"); //解决中文乱码,设置UTF-8不起作用
            stringEntity.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(stringEntity);

            // 发送请求
            HttpResponse response = httpClient.execute(post);

            // 检验返回码
            int code = response.getStatusLine().getStatusCode();
            String body = convertHttpResponseBodyToString(response);
            JSONObject json = JSONObject.parseObject(body);
            String ret = json.getString("success");
            if (ret.equals("true"))
            {
                isSuccess = true;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            isSuccess = false;
        }
        finally
        {
            if (post != null)
            {
                try
                {
                    post.releaseConnection();
                    Thread.sleep(500);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return isSuccess;
    }

 

你可能感兴趣的:(http,json,java,object)