GET请求Demo:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textViewShow = (TextView) findViewById(R.id.showText); //直接在URL后添加请求参数 String url = "http://192.168.1.103/index.php?get1=hello&get2=bay"; try { // 创建DefaultHttpClient对象 HttpClient httpclient = new DefaultHttpClient(); // 创建一个HttpGet对象 HttpGet get = new HttpGet(url); // 获取HttpResponse对象 HttpResponse response = httpclient.execute(get); //判断是否链接成功 if (response.getStatusLine().getStatusCode() == 200) { //实体转换为字符串 String content = EntityUtils.toString(response.getEntity(),"utf-8"); textViewShow.setText(content); }else{ textViewShow.setText("网络错误"); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }POST请求Demo:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textViewShow = (TextView) findViewById(R.id.showText); String url = "http://192.168.1.103/index.php"; HttpClient httpClient = new DefaultHttpClient(); try { HttpPost post = new HttpPost(url); List params = new ArrayList(); params.add(new BasicNameValuePair("get1", "hello")); params.add(new BasicNameValuePair("get2", "usrl")); post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = httpClient.execute(post); if(response.getStatusLine().getStatusCode() ==200){ String content = EntityUtils.toString(response.getEntity(),"utf-8"); textViewShow.setText(content); }else{ textViewShow.setText("网络问题"); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block textViewShow.setText("UnsupportedEncodingException"); } catch (ClientProtocolException e) { // TODO Auto-generated catch block textViewShow.setText("ClientProtocolException"); } catch (IOException e) { // TODO Auto-generated catch block textViewShow.setText("IOException"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
Android使用Apache HttpClient发送GET、POST请求,布布扣,bubuko.com
Android使用Apache HttpClient发送GET、POST请求
原文:http://blog.csdn.net/chenyiming_1990/article/details/21956489