通常与服务器建立连接有两种方法,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; @Override protected 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方法,注意传递参数使用的方法 @Override public void onClick(View arg0) { // TODO Auto-generated method stub String 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 block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { inputStream.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } } }); //这里用到的是Post方法连接服务器,注意传递参数的方法 button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub String 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 block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { inputStream.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } } catch (Exception e) { // TODO: handle exception 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.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>
再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow