HttpClient 连接网络的两种方法doGet和doPost

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 21:02   4440   0

大家都知道android连接网络有两种方式,一种是HttpClient,另一种是HttpURLConnection,下面就先把我自己学习的第一种连网方式HttpClient记录下来,后一种方法有空再记录下来,好记心始终不如烂笔头啊。

android连网分HttpClient和HttpURLConnection两种,而HttpClient又分doGet和doPost两种,HttpURLConnection也分doGet和doPost两种;

一,不管是什么方式连网,都要检查网络的可用性

ConnectivityManager cm = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
  NetworkInfo info = cm.getActiveNetworkInfo();
  if (info != null) {
   Toast.makeText(HttpClientAsyncTaskActivity.this,
     "连网正常" + info.getTypeName(), Toast.LENGTH_SHORT).show();
  } else {
   Toast.makeText(HttpClientAsyncTaskActivity.this, "未连网",
     Toast.LENGTH_SHORT).show();
  }

在写这段代码前一定要先加权限:

    
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
public class HttpClientActivity extends Activity implements OnClickListener {
 private TextView mTextView, mTextView1;
 private Button mButton, mButton1, mButton2,mButton3;
 private EditText mEditText;
 private ProgressDialog pq;
 private String addressurl = "http://192.168.1.196:8080/WebRoot/dogetServlet?name=admins&password=1234";
 // private String addressurl = "http://www.baidu.com";

 private String addressurl1 = "http://192.168.1.196:8080/WebRoot/dogetServlet";

 /**
  * 一get方法 通过get方法获取服务器数据的两个方式HttpClient,HttpURLConnection
  * 传参直接在地址url中加上"?name=admins&password=1234" 传递的参数直接显示出来,不安全
  */
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.http_layout);

  mTextView = (TextView) findViewById(R.id.httpclient_text);
  mTextView1 = (TextView) findViewById(R.id.httpurl_text);
  mButton = (Button) findViewById(R.id.http_httpclient_get_but);
  mButton.setOnClickListener(this);
  mButton1 = (Button) findViewById(R.id.http_httclient_post_but);
  mButton1.setOnClickListener(this);
  mButton2 = (Button) findViewById(R.id.http_httpurl_get_but);
  mButton2.setOnClickListener(this);
  mButton3=(Button) findViewById(R.id.http_httpurl_post_but);
  mButton3.setOnClickListener(this);
  mEditText=(EditText) findViewById(R.id.httpurl_edit);
 }

doPost方法:

/**
  * @param HttpClient POST请求
  */
 public String getContentByHttpClientByPost(String httpurl) {
  try {
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httpPost = new HttpPost(httpurl);
   /** POST组装参数 **/
   BasicNameValuePair userNamePair = new BasicNameValuePair("name",
     "露西");
   BasicNameValuePair passWordPair = new BasicNameValuePair(
     "password", "abcd");
   ArrayList<BasicNameValuePair> Pairlist = new ArrayList<BasicNameValuePair>();
   Pairlist.add(userNamePair);
   Pairlist.add(passWordPair);
   UrlEncodedFormEntity entity = new UrlEncodedFormEntity(Pairlist,
     HTTP.UTF_8);
   httpPost.setEntity(entity);
   httpPost.setHeader("Content-Type",
     "application/x-www-form-urlencoded;charset=utf-8");

   HttpResponse response = httpclient.execute(httpPost);
   int statusCode = response.getStatusLine().getStatusCode();
   Log.d("HttpClient  POST", "statusCode>>>>>>>: " + statusCode);
   if (statusCode == HttpURLConnection.HTTP_OK) {
    String content = EntityUtils.toString(response.getEntity());
    Log.d("HttpClient  POST", "content>>>>>>>>: " + content);
    return content;
   }
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return null;
 }

由于连接网络属于耗时操作,要实现HttpClient通信必须与AsyncTask异步机制结合,AsyncTask异步机制其实就是把线程和Handler消息机制封装的方法,当然这是系统封装好的的类;

case R.id.http_httclient_post_but:

   new AsyncTask<String, Void, String>() {// 实现HttpClient通信与AsyncTask异步机制的结合
    protected String doInBackground(String... params) {
     String url = params[0];

     return getContentByHttpClientByPost(url);
    }

    protected void onPostExecute(String result) {

     if (result != null) {
      mTextView.setText(result);
      Log.v("HttpClient  POST", "onPostExecute>>post:"
        + result);
     }

    }
   }.execute(addressurl1);
   break;


doGet方法:

/**
  * 
  * HttpClient GET请求
  * 
  */
 public String getContentByHttpClient(String httpurl) {
  InputStream in = null;
  try {
   HttpClient httpClient = new DefaultHttpClient();// 实例化HttpClient类
   HttpGet httpGet = new HttpGet(httpurl);// 用get方法请求
   HttpResponse response = httpClient.execute(httpGet);// 执行get请求方法返回
                // response

   int statusCode = response.getStatusLine().getStatusCode();// 通过获取状态行再获取状态码
   Log.v("", "statusCode>>>>>:" + statusCode);

   if (statusCode == HttpURLConnection.HTTP_OK) {// statusCode==200isok

    in = response.getEntity().getContent();// 获取信息内容

    BufferedReader reader = new BufferedReader(
      new InputStreamReader(in, "UTF-8"));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
     sb.append(line);
    }
    Log.v("", "sb.toString():" + sb.toString());
    return sb.toString();
   }

  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (IllegalStateException e) {
   e.printStackTrace();
  } finally {
   if (in != null) {
    try {
     in.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return null;
 }
同样,doGet方法也要与异步机制一起使用:
<pre class="java" name="code">case R.id.http_httpclient_get_but:
   /** 参数组装 **/
   // String urls="http://192.168.1.196:8080/WebRoot/dogetServlet";
   // String parameter="?name=admins&password=1234";
   // String urlss=urls+parameter;
   // Log.v("","url>>>>:"+urlss);

   new AsyncTask<String, Void, String>() {// 实现HttpClient通信与AsyncTask异步机制的结合
    protected String doInBackground(String... params) {
     String url = params[0];

     return getContentByHttpClient(url);
    }

    protected void onPostExecute(String result) {

     if (result != null) {
      mTextView.setText(result);
      // pq.dismiss();// 消除dialog
      Log.v("", "onPostExecute:" + result);
     }

    }
   }.execute(addressurl);
   // pq = ProgressDialog.show(this, "请稍后。。。", "正在请求数据");
   break;

 
权限配置:
<pre class="html" name="code">  <uses-permission android:name="android.permission.INTERNET" />







分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP