0

如果我想从 web api 读取 json,首先我需要将一些 json 发布到服务器中,所以我的代码将是:

   private class AsyncFetch extends AsyncTask<String, String, String> {
      HttpURLConnection conn = null;
      InputStream inputStream = null;
      StringBuffer out = new StringBuffer();
      @Override
        protected String doInBackground(String... params) {
         try {
                URL url = new URL("http://10.54.180.18:8090/TV/api/GetUserInfo");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Authorization", default_token);
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("accountNo", "cb2c2041d9763d84d7d655e81178f444");
            jsonObject.put("stationNo", "NURS4");
            jsonObject.put("bedNo", "329-1");

            DataOutputStream os = new DataOutputStream(conn.getOutputStream());
            os.writeBytes(URLEncoder.encode(jsonObject.toString(), "UTF-8"));

            os.flush();
            os.close();

            //get response
            inputStream = conn.getInputStream();
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[4096];
            for (int n; (n = inputStream.read(b)) != -1;) {
                out.append(new String(b, 0, n));
            }
       } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(conn != null) {
                conn.disconnect();
            }
        }
        return out.toString();

现在我想查看 repose 结果(JSON),我该怎么办?请帮助我,谢谢。

4

1 回答 1

0

使用 AsyncTask 而不是 Thread 将数据发送到服务器。它提供了方法

  1. 预执行()
  2. doInBackround()
  3. onProgressUpdate
  4. 后执行()

覆盖这些方法。在 doInBackground() 方法中编写用于服务器连接的代码。在 postExecute() 上处理结果

创建一个类——MyTask 类扩展 AsyncTask {

protected void onPreExecute() {
    super.onPreExecute();

}

protected String doInBackground(Void...arg0) {
    //String result = write code to connect to server & send data in background thread
    return result;
}

protected void onProgressUpdate(Integer...a) {
    super.onProgressUpdate(a);

}

protected void onPostExecute(String result) {
    super.onPostExecute(result);

}

}

在活动中调用它 new MyTask().execute();

按照链接

https://developer.android.com/reference/android/os/AsyncTask

于 2020-01-17T09:41:45.280 回答