vendredi 30 octobre 2020

Get Website Source Code in Andriod Studio

I am trying to get the source of a website example: "https://www.google.com/" to a textview but the app keeps crashing when i try to open it on my phone so i decided to use firebase lab test I used Galaxy A 2017, API Level 24(It Worked Perfectly) Pixel 2, API Level 27 (It Worked Perfectly) Pixel 2, API Level 28 (It Worked Perfectly) My phone is GIONEE M100 with Android Version 9 (API Level 28) It crashes everytime i try to open it. I also tried it on Redmi Note 8 Android Version 9 (API Level 28) it also crashes I still can't figure out why the same app works perfectly well in firebase lab test on different version and crashes on physical devices. Here is the code

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_website_source_code);

        textView = findViewById(R.id.textView);
        editText = findViewById(R.id.editText);
        button = findViewById(R.id.button);

        textView.setText(getWebsiteSourceCode("https://www.google.com/"));
    }

    public String getWebsiteSourceCode(String website){
        String resString = "";
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(website);
        try{
            HttpResponse response;
            response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "windows-1251"), 8);
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) !=null){
                stringBuilder.append(line + "\n");
            }
            resString = stringBuilder.toString();
            inputStream.close();
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this, "Error!", Toast.LENGTH_SHORT).show();
        }
        return resString;
    }

In Manifest I added

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

In build gradle I added

useLibrary 'org.apache.http.legacy'



Aucun commentaire:

Enregistrer un commentaire