在Android开发中,使用Http协议实现网络之间的通信是随处可见的,使用http方式主要采用2中请求方式即get和post两种方式。
一、使用get方式:
HttpGet httpGet = new HttpGet(url); // 生成一个客户端对象 httpClient = new DefaultHttpClient(); try { // 通过客户端对象httpClient的execute方法执行请求 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) { // TODO Auto-generated catch block e.printStackTrace(); }
二、使用Post方式:
NameValuePair nameValuePair1 = new BasicNameValuePair("name", name); NameValuePair nameValuePair2 = new BasicNameValuePair("age", age); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(nameValuePair1); nameValuePairs.add(nameValuePair2); try { httpEntity = new UrlEncodedFormEntity(nameValuePairs); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(httpEntity); httpClient = new DefaultHttpClient(); try { httpResponse = httpClient.execute(httpPost); 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) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } break; }