79638

how to read and use the content of a website in android app

I actually have to read and use the content of some website in an Android app. I majorly e used two different codes till now to get the content of a website but they did not work for me

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

And

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

Both of these give me exception. The <strong>1st one</strong> gives exception at response = httpclient.execute(httpget) and exception.getMessage() is "null" while the <strong>2nd one</strong> gives exception at httpConn.setAllowUserInteraction(false) and exception.getMessage() is Error connecting. Even I have used Internet permissions in menifest file

Answer1:

This part of code can help you:

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

Recommend

  • react-native-push-notification can not build in android
  • how to wait for a process to end in java or clojure
  • getNodeValue() returns null although response xml holder does not
  • EclEmma, Java8 and Lambda - no coverage on lambda expression
  • C# Getting window's title by handle in Hebrew return question marks
  • Timezone display value with GMT offset from a given timezone?
  • Extract and multiple integers from user-input string in Ruby?
  • java use Regular Expressions to generate a string [duplicate]
  • Java catching exceptions and subclases
  • Why is JSON.NET adding all these backslashes
  • How to read data from socket connection - android
  • How could I write a BsonDocument object into a file, and read it again, using Java
  • C# where to add a method
  • How to convert Neo4j Result to GraphJSON
  • vi mode to emacs mode while on R
  • Crafting a LINQ based solution to determine if a set of predicates are satisfied for a pair of colle
  • Runtime error in UVA Online Judge [closed]
  • how to remove a div with same ids but display='block' and display='none' in JAVa
  • Enabling DTD support in Sql Server
  • msbuild create itemgroup from property group
  • Updating both a ConcurrentHashMap and an AtomicInteger safely
  • Convert SQLite database to XML
  • Reading a file into a multidimensional array
  • WPF Visiblity Binding to Boolean Expression with multiple Variables
  • Conversion from string “a” to type 'Boolean' is not valid
  • Unable to install Git-core+svn by MacPorts
  • Caching attributes in superclass
  • Admob requires api-13 or later can I not deploy on old API-8 phones?
  • Is it possible to access block's scope in method?
  • SignalR .NET Client Invoke throws an exception
  • Spring security and special characters
  • Does CUDA 5 support STL or THRUST inside the device code?
  • Trying to switch camera back to front but getting exception
  • When should I choose bucket sort over other sorting algorithms?
  • How do you troubleshoot character encoding problems?
  • Arrays break string types in Julia
  • WPF Applying a trigger on binding failure
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • Understanding cpu registers
  • Programmatically clearing map cache