Cdacians

Cdacians
Cdacians

Tuesday 7 August 2012

HttpClient and HttpGet


HttpClient and HttpGet

org.apache.http.client.HttpClient is a Interface class for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests.

org.apache.http.client.methods.HttpGet provide HTTP GET method.

A simple example:

HttpClient and HttpGet

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.AndroidHttpGet;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
 
public class AndroidHttpGetActivity extends Activity {
  
 final String httpPath = "http://feeds.feedburner.com/AndroidCoding";
  
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       
       TextView text = (TextView)findViewById(R.id.text);
       
       HttpClient httpclient = new DefaultHttpClient();
       HttpGet httpget = new HttpGet(httpPath);
       try {
 
   HttpEntity httpEntity = httpclient.execute(httpget).getEntity();
    
   if (httpEntity != null){
    InputStream inputStream = httpEntity.getContent();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder stringBuilder = new StringBuilder();
       
    String line = null;
       
    while ((line = bufferedReader.readLine()) != null) {
     stringBuilder.append(line + "\n");
    }
 
    inputStream.close();
       
    text.setText(stringBuilder.toString());
   }
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Toast.makeText(AndroidHttpGetActivity.this, e.toString(), Toast.LENGTH_LONG).show();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Toast.makeText(AndroidHttpGetActivity.this, e.toString(), Toast.LENGTH_LONG).show();
  }
   }
}




akm
www.cdacians.com

No comments:

Post a Comment