通常与服务器建立连接有两种方法,Get和Post方法,下面就对这两个方法进行介绍。

无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源。

1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。

2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。

3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。

如果使用HttpPost方法提交HTTP POST请求,还需要使用HttpPost类的setEntity方法设置请求参数。

下面以一个实例介绍这两个方法的具体实现:

本程序介绍如何通过HttpClient模块来创建Http连接,并分别以Http Get和Post方法传递参数,连接之后取回web server的返回网页结果。

注意,在用Post时,传递变量必须用NameValuePais[]数组存储,通过HttpRequest.setEntity()方法来发出http请求。

此外,也必须通过DefaultHttpClient().execute(httpRequest)添加HttpRequest对象来接收web server的回复,在通过httpResponse.getEntity()取出回复信息。

下图是实现的截图:

具体的实现代码如下:

//使用Get和Post方法向服务器发送请求,其中包含数据
public class MainActivity extends Activity {private Button button;private Button button2;private EditText editText;private TextView textView;private String baseUrl="http://www.baidu.com";private HttpResponse httpResponse;private HttpEntity httpEntity;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button=(Button)findViewById(R.id.button1);button2=(Button)findViewById(R.id.button2);editText=(EditText)findViewById(R.id.edittext);textView=(TextView)findViewById(R.id.textview);button.setOnClickListener(new OnClickListener() {//这里用的是Get方法,注意传递参数使用的方法@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubString userEdit=editText.getText().toString();//如果这里用到的参数不止一个,那个每一个参数都需要用&符号连接String URL=baseUrl+"?"+userEdit;//生成一个请求对象HttpGet httpGet=new HttpGet(URL);//生成一个Http客户端对象HttpClient httpClient=new DefaultHttpClient();//使用Http客户端发送请求对象InputStream inputStream=null;try {httpResponse=httpClient.execute(httpGet);//收到服务器的响应之后把返回的数据读取出来httpEntity=httpResponse.getEntity();inputStream=httpEntity.getContent();//流文件的读取BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));String resultString="";String lineString="";while((lineString=reader.readLine())!=null){resultString=resultString+lineString;}textView.setText(resultString);} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {inputStream.close();} catch (Exception e2) {// TODO: handle exceptione2.printStackTrace();}}}});//这里用到的是Post方法连接服务器,注意传递参数的方法button2.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubString userEdit=editText.getText().toString();//如果传递的参数不止一个,那么就需要用到多个NameValuePair对象NameValuePair nameValuePair=new BasicNameValuePair("userEdit", userEdit);List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();nameValuePairs.add(nameValuePair);try {HttpEntity requestEntity=new UrlEncodedFormEntity(nameValuePairs);HttpPost httpPost=new HttpPost(baseUrl);httpPost.setEntity(requestEntity);HttpClient httpClient =new DefaultHttpClient();InputStream inputStream=null;try {httpResponse=httpClient.execute(httpPost);//另一种获取服务器响应的方法
//                      /*若状态码为200 ok*/
//                        if(httpResponse.getStatusLine().getStatusCode() == 200)
//                        {
//                          /*取出响应字符串*/
//                          String strResult = EntityUtils.toString(httpResponse.getEntity());
//                          textView.setText(strResult);
//                        }
//                        else
//                        {
//                          textView.setText("Error Response: "+httpResponse.getStatusLine().toString());
//                        }
//                      //收到服务器的响应之后把返回的数据读取出来httpEntity=httpResponse.getEntity();inputStream=httpEntity.getContent();//流文件的读取BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));String resultString="";String lineString="";while((lineString=reader.readLine())!=null){resultString=resultString+lineString;}textView.setText(resultString);} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {inputStream.close();} catch (Exception e2) {// TODO: handle exceptione2.printStackTrace();}}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.activity_main, menu);return true;}}

最后,需要在AndroidManifest.xml文件中声明访问网络的权限:

 <uses-permission android:name="android.permission.INTERNET"/>

其中,布局文件的代码如下:

<ScrollView
android:id="@+id/myScrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<LinearLayout xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity" android:orientation="vertical"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="请输入传递给服务器端的参数:" android:textColor="#0000ff"/><EditText android:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/edittext"/><Button android:id="@+id/button1"android:layout_height="wrap_content"android:layout_width="match_parent"android:text="Get方法发送请求"/><Button android:id="@+id/button2"android:layout_height="wrap_content"android:layout_width="match_parent"android:text="Post方法发送请求"/><TextViewandroid:id="@+id/textview"android:layout_width="match_parent"android:layout_height="wrap_content"android:textColor="#ff0000"/></LinearLayout>
</ScrollView>

Android开发--Http操作介绍(二)相关推荐

  1. Android开发--Http操作介绍(一)

    什么是HTTP? 1.超文本传输协议是互联网上应用最为广泛的一种网络协议 2.HTTP是一个客户端和服务器端请求和应答的标准,客户端是终端用户,服务器端是网站 3.HTTP是客户端浏览器或其他应用程序 ...

  2. Android开发笔记(一百二十六)自定义音乐播放器

    MediaRecorder/MediaPlayer 在Android手机上面,音频的处理比视频还要复杂,这真是出人意料.在前面的博文< Android开发笔记(五十七)录像录音与播放>中, ...

  3. Android开发笔记(一百二十三)下拉刷新布局SwipeRefreshLayout

    SwipeRefreshLayout 下拉刷新布局SwipeRefreshLayout是Android又一与时俱进的控件,顾名思义它随着用户手势向下滑动就会触发刷新操作.从实际的下拉效果来看,Swip ...

  4. Android开发笔记(一百二十二)循环器视图RecyclerView

    RecyclerView RecyclerView是Android在support-v7库中新推出控件,中文别名为循环器视图,它的功能非常强大,可分别实现ListView.GridView,以及瀑布流 ...

  5. 【Android开发VR实战】二.播放360°全景视频

    转载请注明出处:http://blog.csdn.net/linglongxin24/article/details/53924006 本文出自[DylanAndroid的博客] [Android开发 ...

  6. Android通知怎么实现?Android开发如何操作相机和相册?

    Android通知怎么实现?Android开发如何操作相机和相册? 前言 八.Android通知怎么实现?Android开发如何操作相机和相册? 8.1 通知介绍 8.2 通知的基本用法 8.3 An ...

  7. Android开发 ---如何操作资源目录中的资源文件2

    Android开发 ---如何操作资源目录中的资源文件2 一.颜色资源管理 效果图: 描述: 1.改变字体的背景颜色 2.改变字体颜色 3.改变按钮颜色 4.图像颜色切换 操作描述: 点击(1)中的颜 ...

  8. Android开发笔记(一百二十四)自定义相册

    画廊Gallery Gallery是一个早期的画廊控件,左右滑动手势可展示内嵌的图片列表,类似于一个平面的万花筒.虽然Android现在将Gallery标记为Deprecation(表示已废弃),建议 ...

  9. android开发那些事儿(二)--Drawable资源

    在Android应用中,常常会用到Drawable资源,比如图片资源等,在Android开发中我们是用Drawable类来Drawable类型资源的. Drawable资源一般存储在应用程序目录的\r ...

最新文章

  1. 【转】如何用Redis做LRU-Cache
  2. Spring boot异常统一处理方法:@ControllerAdvice注解的使用、全局异常捕获、自定义异常捕获
  3. 047_输出一下byte的所有值
  4. Python——[Anaconda+Jupyter Notebook+Python3.6]环境下安装face_recognition
  5. 计算机网络全部实验,计算机网络综合实验
  6. 设置RDLC中table控件的表头在每页显示
  7. 在VMware Workstation中设置双网卡实现SSH使用固定IP登录并且在虚拟系统中任意访问Internet...
  8. Android年月日选择,Android日期选择器实现年月日三级联动
  9. go中的make和new的区别
  10. 即时通信(二)--- 腾讯云IM接入具体实现
  11. 等了十年的微信功能终于成真
  12. 高频交易及化资策与区
  13. Java网络爬虫抓取新浪微博个人微博记录
  14. 第二个版图项目:CD4511
  15. 8、TM4单片机的滴答定时器,及利用定时器精确延时
  16. echarts3.7.1 用例体验地图
  17. 安卓小人html制作,告白小人在线制作
  18. 10分钟go crawler colly从入门到精通
  19. 中间件weblogic部署详情
  20. 邢台市工业机器人集成商_十大优秀工业机器人系统集成商分析

热门文章

  1. java Cache框架
  2. 使用HAProxy、PHP、Redis和MySQL支撑10亿请求每周架构细节
  3. Hibernate最佳实践
  4. asp.net基础复习(二)——母版页
  5. ['1', '2', '3'].map(parseInt) what why ?
  6. Ubuntu14搭建配置青岛大学OJ系统
  7. C++/Php/Python/Shell 程序按行读取文件或者控制台方法总结。
  8. CentOS系统更换软件安装源yum
  9. 推荐一款带暂停功能的轮播组件,不要谢我,我叫红领巾!
  10. Oracle Events事件