ANDROID get content from url

2020-05-06 08:11发布

问题:

I have a problem with Android:

I have to be able to read content from a URL that generates them and then put them in an array Splitting the string read. I have used different methods but I can not read that string. How can I do?

This is the function that I now use (continue to appear the string "nn va"):

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();
        }


    }

the URL to this point: http://www.innovacem.com/public/glace/leggiFoto.php (should write "vuoto")

thanks :)

回答1:

Use async task:

private class ReadTask extends AsyncTask<String, Integer, String> 
{

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

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

To invoke it use:

new ReadTask().execute(<your url>);


回答2:

Try it via this method.

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;
    }

Thanks.



标签: android url