Get text from web page to string

前端 未结 3 1209
感情败类
感情败类 2020-11-27 05:46

I\'m new to Android and I want to get the whole text from a web page to a string. I found a lot of questions like this but as I said I\'m new to Android and I don\'t know ho

3条回答
  •  一整个雨季
    2020-11-27 06:13

    This is the code I generally use to download a string from the internet

    class RequestTask extends AsyncTask{
    
    @Override
    // username, password, message, mobile
    protected String doInBackground(String... url) {
        // constants
        int timeoutSocket = 5000;
        int timeoutConnection = 5000;
    
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        HttpClient client = new DefaultHttpClient(httpParameters);
    
        HttpGet httpget = new HttpGet(url[0]);
    
        try {
            HttpResponse getResponse = client.execute(httpget);
            final int statusCode = getResponse.getStatusLine().getStatusCode();
    
            if(statusCode != HttpStatus.SC_OK) {
                Log.w("MyApp", "Download Error: " + statusCode + "| for URL: " + url);
                return null;
            }
    
            String line = "";
            StringBuilder total = new StringBuilder();
    
            HttpEntity getResponseEntity = getResponse.getEntity();
    
            BufferedReader reader = new BufferedReader(new InputStreamReader(getResponseEntity.getContent()));  
    
            while((line = reader.readLine()) != null) {
                total.append(line);
            }
    
            line = total.toString();
            return line;
        } catch (Exception e) {
            Log.w("MyApp", "Download Exception : " + e.toString());
        }
        return null;
    }
    
    @Override
    protected void onPostExecute(String result) {
        // do something with result
    }
    }
    

    And you can run the task with

    new RequestTask().execute("http://www.your-get-url.com/");

提交回复
热议问题