不使用异步任务调用Web服务

时间:2017-05-15 16:25:55

标签: java android android-asynctask

我需要连接到Web服务并使用Android获取XML输出。 Web服务为给定单词提供英语同义词。以下Java代码由API提供程序提供,

public class Thesaurus {
public static void main(String[] args) {
    new SendRequest("peace", "en_US", "test", "xml");
}
} // end of Thesaurus 

class SendRequest {
    final String endpoint = "http://thesaurus.altervista.org/thesaurus/v1";

    public SendRequest(String word, String language, String key, String output) {
     try {
        URL serverAddress = new URL(endpoint + "?word=" + URLEncoder.encode(word, "UTF-8") + "&language=" + language + "&key=" + key + "&output=" + output);
        HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
        connection.connect();
        int rc = connection.getResponseCode();
        if (rc == 200) {
            String line = null;
            BufferedReader br = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line + '\n');
            }
            System.out.print(sb.toString());
        } else {
            System.out.println("HTTP error:" + rc);
        }
        connection.disconnect();

    } catch (java.net.MalformedURLException e) {
        e.printStackTrace();
    } catch (java.net.ProtocolException e) {
        e.printStackTrace();
    } catch (java.io.IOException e) {
        e.printStackTrace();
    }
 }
} // end of SendRequest

但是,由于在不使用Async任务的情况下无法在Android中执行此操作,因此我修改了以下代码,

class SendRequest extends AsyncTask<Void, Void, Void> {
    final String endpoint = "http://thesaurus.altervista.org/thesaurus/v1";
    final String key = "test";
    final String language = "en_US";
    final String output = "xml";

    @Override
    protected Void doInBackground(Void... params) {
        try {
            URL serverAddress = new URL(endpoint + "?word=" + URLEncoder.encode(text, "UTF-8") + "&language=" + language + "&key=" + key + "&output=" + output);
            HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
            connection.connect();
            int rc = connection.getResponseCode();
            if (rc == 200) {
                String line = null;
                BufferedReader br = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line + '\n');
                }
                synonymTxt = sb.toString();
            } else {
                synonymTxt = "HTTP error:" + rc;
            }
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        AlertDialog ad1 = new AlertDialog.Builder(CreateAppointmentActivity.this).create();
        ad1.setTitle("Synonym Results");
        ad1.setMessage(synonymTxt);
        ad1.setButton(AlertDialog.BUTTON_POSITIVE, "Okay", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        ad1.show();
    }
}

我的问题是后执行块被执行但输出是空的。 Async任务用作内部类,变量“text”和“synonymtxt”是类级变量。我现在已经苦苦挣扎了近12个小时,我唯一的建议是代码不会等到异步任务完成。我怎样才能得到这个的输出?

1 个答案:

答案 0 :(得分:0)

我发现了问题。这是我自己的错。我已将权限放在清单的错误位置。重新定位它们现在可以正常工作