Thursday, February 21, 2019

Java get text from website

To get text from normal web, not txt page, we use this class.
class RequestTask extends AsyncTask<String, String, String>{

     @Override
         
     protected String doInBackground(String... url) {
         
     HttpClient client = new DefaultHttpClient();
     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) {
             
     t.setText(result);
     }
     }
Call inside a progressBar to wait.
mProgressDialog = new ProgressDialog(this);
           mProgressDialog.setMessage("Loading, please wait...");
            mProgressDialog.show();
        new Thread(new Runnable(){
            public void run(){
           
                new RequestTask().execute("http://llkqe.blogspot.com/2016/06/blog-post.html");
                if(mProgressDialog.isShowing())
                {
                   mProgressDialog.dismiss();
                }
            }
        }).start();
    }
new RequestTask().execute("http://llkqe.blogspot.com/2016/06/blog-post.html");
Here is what we get.
To get needed String, we add a special String, here is “Đây” and split, add to arrayList.
Declare arraylist.
ArrayList<String> read = new ArrayList<String>();
Replace code in fuctionc @Override
          protected void onPostExecute(String result) {
by this.
String l=result.toString();
              
String a[] = l.split(" ");
for (int i = 0; i < a.length; i++) {    
if(a[i].equals("Đây")){
read.add(a[i+7]);                    
  }
}
String r="";
for (int i = 0; i < read.size(); i++) {
r=r+read.get(i)+"\n";
}
t.setText(r+"");
Run to see the result.

To avoid crash, check internet connection before open new screen, show Toast to inform user.

No comments:

Post a Comment