首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ANDROID从url获取内容

ANDROID从url获取内容
EN

Stack Overflow用户
提问于 2013-06-24 16:34:04
回答 2查看 11.8K关注 0票数 0

我对Android有一个问题:

我必须能够从生成内容的URL中读取内容,然后将它们放入拆分字符串read的数组中。我使用了不同的方法,但我无法读取该字符串。我该怎么做呢?

这是我现在使用的函数(继续显示字符串"nn va"):

代码语言:javascript
复制
private void vaia () { // funzione vaia *******************************************************

        try {
            HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
            HttpGet httpget = new HttpGet(URL); // Set the action you want to do
            HttpResponse response = httpclient.execute(httpget); // Executeit
            HttpEntity entity = response.getEntity(); 
            InputStream is = entity.getContent(); // Create an InputStream with the response
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) // Read line by line
                sb.append(line + "\n");

            String resString = sb.toString(); // Result is here
            Log.i("string letta", resString);

            is.close(); // Close the stream
        } 
        catch (Exception e) {
            Log.i("Risultato eccezione","nn va");
              //e.printStackTrace();
        }


    }

这里的网址是:http://www.innovacem.com/public/glace/leggiFoto.php (应该写成"vuoto")

谢谢:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-06-24 18:16:58

使用异步任务:

代码语言:javascript
复制
private class ReadTask extends AsyncTask<String, Integer, String> 
{

    @Override
    protected String doInBackground(String... params) 
    {

        getResponseFromUrl(params[0]);
        return "success";
    }   
}

要调用它,请使用:

代码语言:javascript
复制
new ReadTask().execute(<your url>);
票数 1
EN

Stack Overflow用户

发布于 2013-06-24 16:44:10

请通过此方法进行尝试。

代码语言:javascript
复制
public static String getResponseFromUrl(String url) {
        String xml = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xml;
    }

谢谢。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17271147

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档