将 post 发送到服务器并通过 android 获取结果

Send post to server and get result via android

如果我想从网络 api 读取 json ,首先我需要 POST 一些 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 result(JSON) ,我该怎么办?请帮助我,谢谢。

使用 AsyncTask 而不是 Thread 将数据发送到 server.It 提供方法

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

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

上的结果

创建一个class-- class 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);

}

}

在activity中调用它 新的 MyTask().execute();

点击链接

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