android - 如何在Android应用程序中读取和使用网站内容

标签 android android-webview android-internet

我实际上必须在 Android 应用程序中阅读和使用某些网站的内容。到目前为止,我主要使用两种不同的代码来获取网站的内容,但它们对我不起作用

public static String connect(String url)
{
    String result = "bubububu" ;

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(url); 

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        Log.i("Praeda",response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            result= convertStreamToString(instream);
            // now you have the string representation of the HTML request
            instream.close();
            return result ;
        }


    } catch (Exception e) {
        e.getMessage() ;
    }

    return result ;
}

    private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}


public static String connect(String url)
{
    String result = "bubububu" ;

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(url); 

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        Log.i("Praeda",response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            result= convertStreamToString(instream);
            // now you have the string representation of the HTML request
            instream.close();
            return result ;
        }


    } catch (Exception e) {
        e.getMessage() ;
    }

    return result ;
}

    private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

还有

private String DownloadText(String URL)
{
    int BUFFER_SIZE = 2000;
    InputStream in = null;
    try {
        in = OpenHttpConnection(URL);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return "";
    }

    InputStreamReader isr = new InputStreamReader(in);
    int charRead;
    String str = "";
    char[] inputBuffer = new char[BUFFER_SIZE];          
    try {
        while ((charRead = isr.read(inputBuffer))>0)
        {                    
            //---convert the chars to a String---
            String readString = String.copyValueOf(inputBuffer, 0, charRead);
            str += readString;
            inputBuffer = new char[BUFFER_SIZE];
        }
        in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "";
    }    
    return str;        
}

private InputStream OpenHttpConnection(String urlString) 
        throws IOException
        {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString); 
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))                     
        throw new IOException("Not an HTTP connection");

    try{
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect(); 

        response = httpConn.getResponseCode();                 
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();                                 
        }                     
    }
    catch (Exception ex)
    {
        throw new IOException("Error connecting");            
    }
    return in;     
        }

这两个都给了我异常(exception)。 第一个给出了异常(exception) response = httpclient.execute(httpget) 和Exception.getMessage() 为“null”,而第二个 在httpConn.setAllowUserInteraction(false) 处给出异常,并且exception.getMessage() 是连接错误。即使我在menifest文件中使用了互联网权限

最佳答案

这部分代码可以帮助您:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new HttpTask().execute("http://www.google.com");
}


public String getWebPage(String adresse) {

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet();

    InputStream inputStream = null;

    String response = null;

    try {

        URI uri = new URI(adresse);
        httpGet.setURI(uri);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        int statutCode = httpResponse.getStatusLine().getStatusCode();
        int length = (int) httpResponse.getEntity().getContentLength();

        Log.v(LOG_THREAD_ACTIVITY, "HTTP GET: " + adresse);
        Log.v(LOG_THREAD_ACTIVITY, "HTTP StatutCode: " + statutCode);
        Log.v(LOG_THREAD_ACTIVITY, "HTTP Lenght: " + length + " bytes");

        inputStream = httpResponse.getEntity().getContent();
        Reader reader = new InputStreamReader(inputStream, "UTF-8");

        int inChar;
        StringBuffer stringBuffer = new StringBuffer();

        while ((inChar = reader.read()) != -1) {
            stringBuffer.append((char) inChar);
        }

        response = stringBuffer.toString();

    } catch (ClientProtocolException e) {
        Log.e(LOG_THREAD_ACTIVITY, "HttpActivity.getPage() ClientProtocolException error", e);
    } catch (IOException e) {
        Log.e(LOG_THREAD_ACTIVITY, "HttpActivity.getPage() IOException error", e);
    } catch (URISyntaxException e) {
        Log.e(LOG_THREAD_ACTIVITY, "HttpActivity.getPage() URISyntaxException error", e);
    } finally {
        try {
            if (inputStream != null)
                inputStream.close();

        } catch (IOException e) {
            Log.e(LOG_THREAD_ACTIVITY, "HttpActivity.getPage() IOException error lors de la fermeture des flux", e);
        }
    }

    return response;
}

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

    @Override
    protected String doInBackground(String... urls) {
        // TODO Auto-generated method stub
        String response = getWebPage(urls[0]);
        return response;
    }

    @Override
    protected void onPostExecute(String response) {
        Log.i(LOG_THREAD_ACTIVITY, "HTTP RESPONSE" + response);
        textViewConsole.setText(response);
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }

}

关于android - 如何在Android应用程序中读取和使用网站内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16723714/

相关文章:

安卓崩溃报告

android - MVVMCross Native Android Progressbar 使用当前进度移动元素

java - 在 Android 中使用 WebView 访问麦克风

android - 方法 `WebViewClient.onReceivedLoginRequest`有什么作用

java - 如何使用发送的项目特定数据切换 Activity

android - 使用 jacoco 和 gradle 从多模块项目的覆盖范围中排除

android - Webview 不显示古吉拉特语字体

Android 使用其 URL 检查文件是否存在于远程服务器中

android - Android 应用程序中的互联网权限问题?

java - 如何以编程方式忘记android中的无线网络?