Android开发--Http操作介绍(二)

来源:互联网 发布:自然知彼孕妇可以用吗 编辑:程序博客网 时间:2024/05/17 02:04

通常与服务器建立连接有两种方法,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"/>

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

<ScrollViewandroid: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"    >    <TextView        android: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方法发送请求"        />        <TextView        android:id="@+id/textview"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:textColor="#ff0000"   /></LinearLayout></ScrollView>


原创粉丝点击