为什么从getResult获取空值

时间:2019-01-17 16:14:47

标签: java android

我想获取getServerResult()方法的结果,但返回“ null”。但是,httpURLConnectionPost()方法中的Logcat是正常的,返回“成功”。请回答我!在这种情况下,为什么在带有getServerResult()方法的httpURLConnectionPost()方法之外没有null?

private String serverResult;

public void httpURLConnectionPost(final String urlString){
    new Thread(new Runnable() {
        public void run() {
            try {
                URL url = new URL(urlString);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.connect();

                String body = stringBuilder();

                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
                writer.write(body);
                writer.close();

                int responseCode = connection.getResponseCode();
                if(responseCode == HttpURLConnection.HTTP_OK){
                    InputStream inputStream = connection.getInputStream();

                    String line;
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));               

                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilderResult.append(line);
                    }
                    String result = stringBuilderResult.toString();
                    Log.d("MSG","result= "+result);
                    setServerResult(result);
                }
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
    }).start();
}

public void setServerResult(String serverResult){
    this.serverResult = serverResult;
}

public String getServerResult(){
    return serverResult;
}

D / MSG:结果=成功

使用getServerResult(): D / TAG:结果=空

1 个答案:

答案 0 :(得分:2)

您在哪里致电httpURLConnectionPost?无论您应该为此使用异步任务,调用HTTP请求的函数都不会返回任何内容,因为代码在接收到响应之前正在执行并完成。
在尝试获取任何数据之前,您需要确保任务已完成。通常,您将使用异步任务,并在onPostExecute部分中执行一些操作,以使应用程序知道返回了数据。