Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the Simple HTTP client in Android? [closed]

Tags:

android

http

How do I use the AndroidHttpClient as an HTTP client to connect to a remote server? I have not been able to find good examples in the documentation nor on the internet.

like image 584
user538626 Avatar asked Dec 16 '10 04:12

user538626


People also ask

What is HttpClient Android?

HttpClient is used when you want to receive and send data from the server over the internet. So for this you need to create a http client using HttpClient class. First, you will create the object of Http client and the URL to the constructor of HttpPost class that post the data.

What does an HttpClient do?

An HTTP Client. An HttpClient can be used to send requests and retrieve their responses. An HttpClient is created through a builder . The builder can be used to configure per-client state, like: the preferred protocol version ( HTTP/1.1 or HTTP/2 ), whether to follow redirects, a proxy, an authenticator, etc.


1 Answers

public static void connect(String url) {      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();             String result= convertStreamToString(instream);             // now you have the string representation of the HTML request             instream.close();         }       } catch (Exception e) {} }      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(); } 
like image 83
Cristian Avatar answered Sep 22 '22 11:09

Cristian