什么是我的AsyncTask Java代码错误

时间:2018-03-13 23:49:06

标签: java android android-asynctask

我正在尝试使用下面的代码使用AsyncTask从后台的Web服务器读取数据,但它不会返回我希望它返回的消息。

private class MyAsyncTask extends AsyncTask<String, Void, String> {
    String message;
    @Override
    protected String doInBackground(String... date) {
        try {
            URL checkIfBooked = new URL("http://10.0.2.2:80/folder/script.php");
            try {
                HttpURLConnection conn = (HttpURLConnection) checkIfBooked.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches(false);
                String urlParameters = "date=" + date;
                byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
                OutputStream os = conn.getOutputStream();
                os.write(postData);
                os.flush();
                os.close();
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));
                    String inputLine;
                    StringBuilder response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    conn.disconnect();
                    message = response.toString();
                } else {
                    // error
                    //TODO: let the user know that something is wrong with the network
                }
            } catch (java.io.IOException e) {
                //TODO: prevent app from crashing
            }
        } catch (java.net.MalformedURLException e) {
            //TODO: prevent app from crashing
        }
        return message;
    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
    }

}

但是,如果我使用以下方法执行此操作,则会收到返回消息,即“项目已被预订...” 方法:

    void checkIfExists(String date){
    try {
        URL checkIfBooked = new URL("http://10.0.2.2:80/folder/script.php");
        try {
            HttpURLConnection conn = (HttpURLConnection) checkIfBooked.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches (false);
            String urlParameters  = "date=" + date;
            byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
            OutputStream os = conn.getOutputStream();
            os.write(postData);
            os.flush();
            os.close();
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                conn.disconnect();
                Toast.makeText(this, response.toString(), Toast.LENGTH_LONG).show();
            } else {
                // error
                //TODO: let the user know that something is wrong with the network
            }
        } catch (java.io.IOException e) {
            //TODO: prevent app from crashing
        }
    } catch (java.net.MalformedURLException e){
        //TODO: prevent app from crashing
    }
}

我使用new MyAsyncTask().execute(DATE);调用MyAsyncTask,但它返回一个空字符串, 我以checkIfExists的方式致电checkIfExists(DATE)并且它有效。 请注意,日期是最后一个字符串“2018-03-14”。欢迎任何帮助。感谢。

1 个答案:

答案 0 :(得分:0)

doInBackground(String... date)中的AsyncTask方法接受String varargs,但您将其视为单个项目。

String urlParameters = "date=" + date;中的这一行AsyncTask应为:String urlParameters = "date=" + date[0]; - 假设只有1 String通过。

我怀疑你得到一个空的String,因为这行if(responseCode == HttpURLConnection.HTTP_OK) ...是假的(如果script.php实际上做了一些解析?)并返回未初始化的实例变量。