阳光网驿-企业信息化交流平台【DTC零售连锁全渠道解决方案】

 找回密码
 注册

QQ登录

只需一步,快速开始

扫描二维码登录本站

手机号码,快捷登录

老司机
查看: 2808|回复: 0

[转帖] Android中使用HTTPClient进行网络通讯的例子(Android HttpClient use example)

[复制链接]
  • TA的每日心情
    开心
    2021-8-30 00:00
  • 签到天数: 35 天

    [LV.5]常住居民I

    发表于 2011-10-29 20:55:28 | 显示全部楼层 |阅读模式
    很不错的一个教程,推荐初学者学习一下。

    如何在Android中访问网页和网站通讯,进行数据交互呢?答案是使用HTTPClient。

    HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。现在HttpClient最新版本为 HttpClient 4.0.3

    界面定义的XML。

    复制代码

    • <?xml version="1.0" encoding="utf-8"?>
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          androidrientation="vertical" android:layout_width="fill_parent"
          android:layout_height="fill_parent">
          <Button android:text="GET" android:id="@+id/Button01"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content">
          </Button>
          <Button android:text="OST" android:id="@+id/Button02"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content">
          </Button>
          <TextView android:id="@+id/TextView" android:layout_width="fill_parent"
              android:layout_height="wrap_content"/>
      </LinearLayout>



    Activity的代码

    复制代码

    • package com.Aina.Android;

      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.InputStreamReader;
      import java.io.UnsupportedEncodingException;
      import java.net.HttpURLConnection;
      import java.net.MalformedURLException;
      import java.net.URL;
      import java.util.ArrayList;
      import java.util.List;

      import org.apache.http.HttpEntity;
      import org.apache.http.HttpResponse;
      import org.apache.http.HttpStatus;
      import org.apache.http.NameValuePair;
      import org.apache.http.client.ClientProtocolException;
      import org.apache.http.client.HttpClient;
      import org.apache.http.client.entity.UrlEncodedFormEntity;
      import org.apache.http.client.methods.HttpGet;
      import org.apache.http.client.methods.HttpPost;
      import org.apache.http.impl.client.DefaultHttpClient;
      import org.apache.http.message.BasicNameValuePair;
      import org.apache.http.util.EntityUtils;

      import android.app.Activity;
      import android.os.Bundle;
      import android.os.Handler;
      import android.os.Message;
      import android.view.View;
      import android.widget.Button;
      import android.widget.TextView;

      public class Test extends Activity implements Runnable{
          /** Called when the activity is first created. */
          private Button btn_get = null;
          private Button btn_post = null;
          private TextView tv_rp = null;
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
              btn_get = (Button) this.findViewById(R.id.Button01);
              btn_post = (Button) this.findViewById(R.id.Button02);
              tv_rp = (TextView) this.findViewById(R.id.TextView);
              btn_get.setOnClickListener(new Button.OnClickListener(){

                  public void onClick(View v) {
                      // TODO Auto-generated method stub
                      String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp?par=request-get";
                      HttpGet request = new HttpGet(httpUrl);
                      HttpClient httpClient = new DefaultHttpClient();
                      try {
                          HttpResponse response = httpClient.execute(request);
                          if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
                              String str = EntityUtils.toString(response.getEntity());
                              tv_rp.setText(str);
                          }else{
                              tv_rp.setText("请求错误");
                          }
                      } catch (ClientProtocolException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();   
                      } catch (IOException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }
                  }
                  
              });
              btn_post.setOnClickListener(new Button.OnClickListener(){

                  public void onClick(View v) {
                      // TODO Auto-generated method stub
                      String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp";
                      HttpPost request = new HttpPost(httpUrl);
                      List<NameValuePair> params = new ArrayList<NameValuePair>();
                      params.add(new BasicNameValuePair("par","request-post"));
                      try {
                          HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
                          request.setEntity(entity);
                          HttpClient client = new DefaultHttpClient();
                          HttpResponse response = client.execute(request);
                          if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
                              String str = EntityUtils.toString(response.getEntity());
                              tv_rp.setText(str);
                          }else{
                              tv_rp.setText("请求错误");
                          }
                      } catch (UnsupportedEncodingException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      } catch (ClientProtocolException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      } catch (IOException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }
                  }
                  
              });
              new Thread(this).start();
          }
          public void refresh(){
              String httpUrl = "http://192.168.0.132:8080/Android/httpreq.jsp";
              try {
                  URL url = new URL(httpUrl);
                  HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                  urlConn.connect();
                  InputStream input = urlConn.getInputStream();
                  InputStreamReader inputreader = new InputStreamReader(input);
                  BufferedReader reader = new BufferedReader(inputreader);
                  String str = null;
                  StringBuffer sb = new StringBuffer();
                  while((str = reader.readLine())!= null){
                      sb.append(str).append("\n");
                  }
                  if(sb != null){
                      tv_rp.setText(sb.toString());
                  }else{
                      tv_rp.setText("NULL");
                  }
                  reader.close();
                  inputreader.close();
                  input.close();
                  reader = null;
                  inputreader = null;
                  input = null;
              } catch (MalformedURLException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
          public Handler handler = new Handler(){
              public void handleMessage(Message msg){
                  super.handleMessage(msg);
                  refresh();
              }
          };
          public void run() {
              // TODO Auto-generated method stub
              while(true){
                  try {
                      Thread.sleep(1000);
                      handler.sendMessage(handler.obtainMessage());
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }
          }
      }



    XML文件

    复制代码

    • <?xml version="1.0" encoding="utf-8"?>
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.Aina.Android"
            android:versionCode="1"
            android:versionName="1.0">
          <application android:icon="@drawable/icon" android:label="@string/app_name">
              <activity android:name=".Test"
                        android:label="@string/app_name">
                  <intent-filter>
                      <action android:name="android.intent.action.MAIN" />
                      <category android:name="android.intent.category.LAUNCHER" />
                  </intent-filter>
              </activity>

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

      </manifest>




    该贴已经同步到 sunwy的微博
    楼主热帖
    启用邀请码注册,提高发帖质量,建设交流社区
    您需要登录后才可以回帖 登录 | 注册

    本版积分规则

    快速回复 返回顶部 返回列表