java - 如何从 AsyncTask 传回 http 请求的结果?

标签 java android http android-asynctask

我是 Android 和 Java 的初学者。到目前为止做得还不错,但我偶然发现了一个我无法理解的问题。

我正在尝试在我的应用程序类中创建一个方法,该方法将使用传递给它的值对列表进行 http 调用。这是第一部分。这是通过单击按钮激活的 Activity 。

  // Add your data to array
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("action", "2"));
        nameValuePairs.add(new BasicNameValuePair("cell", "2500270025"));
        nameValuePairs.add(new BasicNameValuePair("date", "blah"));
        nameValuePairs.add(new BasicNameValuePair("time", "AndDev is Cool!"));
        nameValuePairs.add(new BasicNameValuePair("reason", "2"));

        // need to call the request
        String result = ((RespondApp) getApplication()).makeHTTPCall(nameValuePairs);

一旦我进入应用程序,这里就是接收部分。

public String makeHTTPCall(List<NameValuePair> nameValuePairs) {
        // this will be used to make all http requests from the whole app       
        new postToHttp().execute(nameValuePairs);
        return null;        
    }

这是 AsyncTask 部分。

class postToHttp extends AsyncTask<List<NameValuePair>, Void, String> {

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // I am sure I need something here just don't know what
        }

        @Override
        protected String doInBackground(List<NameValuePair>... params) {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.evfd.ca/cell.php");
            try {

                httppost.setEntity(new UrlEncodedFormEntity(params[0]));
                Log.i("makeHttpCall", "done ecoding");
                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream instream = entity.getContent();
                String result = convertStreamToString(instream);
                Log.i("Read from server", result);
                return result;
                }

            } catch (ClientProtocolException e) {
                return null;
            } catch (IOException e) {
                return null;
            }
            return null;
        }

我试图将网络服务器发送回的响应一直返回到调用此进程的 Activity 页面。因此,理想情况下,我只想加载值对进行调用并获取 http 响应,然后继续我的快乐之路。

我该怎么做?

最佳答案

您可以直接从 AsyncTask 本身使用在主 UI 线程上下载的 String。只需在 AsyncTask 类中重写 protected void onPostExecute(String result) 并在那里完成工作即可。无论您从 doInBackground() 返回什么值,都会调用此函数。

基本上,执行 onPostExecute() 内的下一步操作。请参阅How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?一些想法:

  • AsyncTask 类作为内部类嵌套在您的 Activity 中,以便它可以与您的 Activity 的变量、方法等一起使用。

    <
  • 创建您的 Activity 实现的接口(interface)。基本上,任务会在 Activity 中调用类似 onHttpTaskComplete(String result) 的内容。

关于java - 如何从 AsyncTask 传回 http 请求的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13999222/

相关文章:

java - 应在我的应用程序中检查哪些 HTTP 状态代码

java - 底部导航栏被 ScrollView 布局推出 View 之外

node.js - _http_server.js :192 throw new RangeError (`Invalid status code: ${statusCode}` );

java - 即使在 list 中声明 Activity 也未找到异常

java - 如何让 Java 中的方法接受类类型变量?

java - struts-config.xml 文件的 action 元素中的 scope 属性有多少可用值

java - 如何在Qt中使用JNI创建字符串数组

java - 在我的服务中,我想通过另一个服务加载路径

javascript - 如何在网站中做向导?

java - 具有多个查询的 jdbcTemplate 查询 - spring boot