HttpClient提交数据

用代码模拟浏览器的行为

* 轻量级的开源的框架

* Android6.0 23 以后移除了httpclient ,所以开发中用的少了

* 编写步骤:

1. 打开浏览器

2. 输入网址

3. 敲回车

 


HttpClient中的类:

HttpClient :想服务器提交数据或者接受服务器返回的数据
NameValuePair :post方式提交数据的键值对
UrlEncodedFormEntity :经过form表单编码的数据实体
HttpResponse :Http响应的 响应头和响应体
StatusLine :状态行
HttpEntity :服务器返给客户端的数据实体

 

GET请求示例代码: 

import java.io.InputStream;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
   private EditText   etPwd;
   private EditText   etQQ;
   private String     pwd;
   private String     qq;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      etPwd = (EditText) findViewById(R.id.et_pwd);
      etQQ = (EditText) findViewById(R.id.et_qq);
   }
   /**
    * 1. 在子线程中进行网络通讯 2. 获取服务器返回的信息 3. 用Handler去展示服务器返回的信息
    */
   public void login(View v) {
      pwd = etPwd.getText().toString().trim();
      qq = etQQ.getText().toString().trim();
      if (TextUtils.isEmpty(pwd) || TextUtils.isEmpty(qq)) {
         Toast.makeText(this, "亲,请输入QQ号码或者密码! :) ", 0).show();
         return;
      }

   // 开启子线程

      new Thread() {
         public void run() {
            requestNetWork();
         };
      }.start();
   }
   /**
    * 网络通信
    */
   private void requestNetWork() {
      try {
         String path = "http://192.168.25.70:8080/web/LoginServlet?" + "qq="
                + URLEncoder.encode(qq) + "&pwd=" + URLEncoder.encode(pwd, "utf-8");
         // 1. 打开浏览器
         HttpClient client = new DefaultHttpClient();
         // 2. 输入网址
         HttpGet urlGet = new HttpGet(path);
         // 3. 敲回车
         HttpResponse response = client.execute(urlGet);
         //状态行
         StatusLine statusLine = response.getStatusLine();
         //状态码
         int code = statusLine.getStatusCode();
         if (code == 200) {
            // * 2xxx 请求成 3xxx重定向 4xxx资源错误 5xxx服务器错误
            // 获取服务器返回的二进制输入流
            //响应体
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            // 把流转成字符串
            String text = StringUtils.parseStream2String(is);
            showToast(text);
         } else {
            showToast(code + "");
         }
      } catch (Exception e) {
         e.printStackTrace();
         showToast("服务器忙!");
      }
   }
   /**
    * 在任意线程弹土司
    */
   public void showToast(final String text) {
      this.runOnUiThread(new Runnable() {
         @Override
         public void run() {
            Toast.makeText(MainActivity.this, text, 0).show();
         }
      });
   }
}

POST请求示例代码: 
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {

   private EditText   etPwd;
   private EditText   etQQ;
   private String     pwd;
   private String     qq;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      etPwd = (EditText) findViewById(R.id.et_pwd);
      etQQ = (EditText) findViewById(R.id.et_qq);
   }
   /**
    * 1. 在子线程中进行网络通讯
    *  2. 获取服务器返回的信息 
    *  3. 用Handler去展示服务器返回的信息
    */
   public void login(View v) {
      pwd = etPwd.getText().toString().trim();
      qq = etQQ.getText().toString().trim();
      if (TextUtils.isEmpty(pwd) || TextUtils.isEmpty(qq)) {
         Toast.makeText(this, "亲,请输入QQ号码或者密码! :) ", 0).show();
         return;
      }
      // 开启子线程
      new Thread() {
         public void run() {
            requestNetWork();
         };
      }.start();
   }
   /**
    * 网络通信
    */
   private void requestNetWork() {
      try {
         String path = "http://192.168.3.100:8080/web/LoginServlet";
         // 1. 打开浏览器
         HttpClient client = new DefaultHttpClient();
         // 2. 输入网址
         HttpPost urlPost = new HttpPost(path);
//       String data = "qq="+URLEncoder.encode(qq)+"&pwd="+URLEncoder.encode(pwd, "utf-8");
         //要提交的数据
         List<NameValuePair> parameters = new ArrayList<NameValuePair>();
         parameters.add(new BasicNameValuePair("qq", qq));
         parameters.add(new BasicNameValuePair("pwd", pwd));
         //经过Url表单编码
         UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(parameters,"utf-8");
         //设置要提交的数据
         urlPost.setEntity(urlEncodedFormEntity);     
         // 3. 敲回车
         HttpResponse response = client.execute(urlPost);
         //状态行
         StatusLine statusLine = response.getStatusLine();
         //状态码
         int code = statusLine.getStatusCode();
         if (code == 200) {
            // * 2xxx 请求成 3xxx重定向 4xxx资源错误 5xxx服务器错误
            // 获取服务器返回的二进制输入流
            //响应体
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            // 把流转成字符串
            String text = StringUtils.parseStream2String(is);
            showToast(text);

         } else {

            showToast(code + "");
         }
      } catch (Exception e) {
         e.printStackTrace();
         showToast("服务器忙!");
      }
   }
   /**
    * 在任意线程弹土司
    */

   public void showToast(final String text) {
      this.runOnUiThread(new Runnable() {
         @Override
         public void run() {
           Toast.makeText(MainActivity.this, text, 0).show();
         }
      });
   }
}

 


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
/**
 * 操作字符串
 */

public class StringUtils {
   /**
    * 从流中转成字符串 
    * @param is
    *            输入流
    * @return null表示失败
    */
   public static String parseStream2Str(InputStream is) {
      //内存输出流
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int len = -1;
      byte[] buffer = new byte[1024*8];
      try {
         while((len = is.read(buffer)) != -1){
            baos.write(buffer, 0, len);
         }
         return new String(baos.toByteArray());
      } catch (Exception e) {
         e.printStackTrace();
         return null;
      }
   }
}

 


posted on 2017-02-23 11:15  LoaderMan  阅读(196)  评论(0编辑  收藏  举报

导航