Advertisement
n0tmE

HttpURLConnection vs HttpClient

Aug 6th, 2011
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. public class TestActivity extends Activity {
  2.     @Override
  3.     public void onCreate(Bundle savedInstanceState) {
  4.         super.onCreate(savedInstanceState);
  5.         setContentView(R.layout.main);
  6.        
  7.         String urlString = "http://yourserver.com/path/to/resource";
  8.         TextView textView;        
  9.         HttpURLConnection conn;
  10.         InputStream is;
  11.        
  12.         try {
  13.             conn = (HttpURLConnection) new URL(urlString).openConnection();
  14.             is = conn.getInputStream();
  15.             textView = (TextView) findViewById(R.id.text1);
  16.             textView.setText(readInputStream(is));
  17.         } catch (MalformedURLException e1) {
  18.             e1.printStackTrace();
  19.         } catch (IOException e1) {
  20.             e1.printStackTrace();
  21.         }
  22.        
  23.          HttpClient client = new DefaultHttpClient();
  24.             HttpGet request = new HttpGet(urlString);
  25.             try{
  26.                 HttpResponse response = client.execute(request);
  27.                 textView = (TextView) findViewById(R.id.text2);
  28.                 is = response.getEntity().getContent();
  29.                 textView.setText(readInputStream(is));
  30.             }catch(Exception ex){
  31.                 ex.printStackTrace();
  32.             }
  33.        
  34.  
  35.     }
  36.    
  37.     private  String readInputStream(InputStream is) throws IOException {
  38.         StringBuffer stream = new StringBuffer();
  39.         byte[] b = new byte[4096];
  40.         for (int n; (n = is.read(b)) != -1;) {
  41.             stream.append(new String(b, 0, n));
  42.         }
  43.         return stream.toString();
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement