当前位置: 首页 > 面试题库 >

如何在Android上建立异步URL连接?

后学
2023-03-14
问题内容

我正在使用以下类连接到我的Web服务。我想使这个异步。我怎样才能做到这一点?

package org.stocktwits.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class RestClient{

    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }


    /* This is a test function which will connects to a given
     * rest service and prints it's response to Android Log with
     * labels "Praeda".
     */
    public static JSONObject connect(String url)
    {

        HttpClient httpclient = new DefaultHttpClient();


        // Prepare a request object
        HttpGet httpget = new HttpGet(url);

        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            // Examine the response status
            Log.i("Praeda",response.getStatusLine().toString());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);

                // A Simple JSONObject Creation
                JSONObject json=new JSONObject(result);

                // Closing the input stream will trigger connection release
                instream.close();

                return json;
            }


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

}

问题答案:

除了Ladlestein评论中的所有可能解决方案之外,还有一个简单的答案将所有内容包装在AsyncTask



 类似资料:
  • 问题内容: 我试图理解,我在我的应用程序中使用。我在中编写了以下代码: 我在Windows Xp OS中将4型jdbc连接与oracle 10g EE一起使用 然后我按如下方式检索servlet: 是它还是需要某些配置? 问题答案: 您可以获得第三方库,也可以使用连接池为您提供的Java EE容器(例如,JBoss或WebSphere)。 为此,您可以配置和使用JNDI数据源。 以下是Tomcat

  • 问题内容: 在受到谴责之前,请阻止已建立的异常连接。谁可以给我解决方案 问题答案: 那是因为必须在建立连接之前调用该函数。检查此链接 http://developer.android.com/reference/java/net/HttpURLConnection.html#setRequestMethod(java.lang.String) 因此最好在openConnection()之前调用它。

  • 问题内容: 有人可以提供有关如何建立JDBC连接池的示例或链接吗? 从搜索谷歌,我看到这样做的许多不同方式,这相当令人困惑。 最终,我需要代码来返回一个对象,但是我在入门时遇到了麻烦。欢迎任何建议。 更新: 没有或没有池连接实现?为什么不最好使用这些? 问题答案: 如果你需要一个独立的连接池,那么我首选的是C3P0而不是DBCP(我在上一个答案中已经提到),在重负载下我对DBCP的问题太多了。使用

  • 是否有人成功地在部署在Kubernetes集群中的Quarkus应用程序中设置了与Keycloack的OIDC连接?您能说明(和其他相关参数)是如何工作的吗?(以下是我试图遵循的文档) 当POD启动时,这些味精会出现在它的日志中: 2021-07-26 14:44:22,523 INFO[main][oidcrecorder.java:264]-每2秒连接IDP最多180次 2021-07-26

  • 问题内容: 谁能推荐一些在python中建立ssh连接的东西?我需要它与任何操作系统兼容。 我已经尝试使用pyssh来获取SIGCHLD的错误,我读过这是因为Windows缺少此错误。我尝试过使paramiko正常工作,但是在paramiko和Crypto之间存在错误,以至于每个版本的最新版本都无法协同工作。 Windows计算机上当前使用Python 2.6.1。 问题答案: 请注意,这在Win

  • 问题内容: 我迷上了Firefox。我无法使Websocket正常工作。我使用TornadoWebsocket,并通过以下代码对其进行了初始化: 然后像这样在Javascript端初始化它: 这段代码在Chrome上运行良好,同时我自己创建了证书并在HTTPS下运行页面。但是Firefox一直在说: 我用谷歌搜索,发现了太多想法,但没有一个对我有用:( 任何帮助将不胜感激。 问题答案: 我通过Pr