package com.example.http01; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Button r_b = null; private HttpResponse httpResponse = null; private HttpEntity httpEntity = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); r_b = (Button)findViewById(R.id.requestbutton); r_b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { HttpGet httpget = new HttpGet("https://www.baidu.com"); HttpClient httpclient = new DefaultHttpClient(); InputStream inputStream = null; try{ httpResponse = httpclient.execute(httpget); httpEntity = httpResponse.getEntity(); inputStream = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String result = ""; String line = ""; while((line = reader.readLine()) != null) result = result line; System.out.println(result); } catch(Exception e){ e.printStackTrace(); } finally{ try{ inputStream.close(); } catch(Exception e){ e.printStackTrace(); } } } }); } }
评论