Android端与Java端的数据交互

Android从第三方项目获取数据通常使用这两种方式

  1,xml格式的数据交互(对xml进行解析获取数据)

  2,json格式的数据交互(对json格式数据进行解析,使用HttpClient技术访问后台代码)

HttpClient的使用步骤
3. HttpClient的使用步骤
  3.1 创建HttpClient对象
      HttpClient httpClient = new DefaultHttpClient();

  3.2 创建HttpGet(或HttpPost)对象
      HttpGet HttpGet = new HttpGet("http://www.baidu.com");
      HttpPost httpPost = new HttpPost("http://www.baidu.com");

  3.3 添加参数(可选)
      setParams(HttpParams params)//HttpGet和HttpPost共有
      setEntity(HttpEntity entity)//HttpPost独有
      
  3.4 发送GET(或POST)请求,并获得响应
      HttpResponse httpResponse = httpClient.execute(HttpUriRequest request);
 
      注1:HttpUriRequest为HttpGet和HttpPost的父类
      注2:需要添加允许网络访问权限,不然会报错“java.lang.SecurityException: Permission denied (missing INTERNET permission?)”
           <uses-permission android:name="android.permission.INTERNET" />

      注3:如果地址错误,或服务器未开户,HttpClient这SB会等待N久(>24小时)。 

            Request sent数据请求时间;Waiting数据响应时间,

           注:多注意Request sent和Waiting时间的长短,如这两种时间超时明显过长可能是第三方数据发生了地址性的变化

           所以请记得设置超时时间,所以请记得设置超时时间,所以请记得设置超时时间
           所以请记得设置超时时间,所以请记得设置超时时间,所以请记得设置超时时间
           所以请记得设置超时时间,所以请记得设置超时时间,所以请记得设置超时时间

           另外HttpClient版本不一样,代码也不一样。下面的4.0版本的写法
           httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);// 连接时间
           httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);// 数据传输时间

  3.5 处理响应
    3.5.1 响应状态码(200)
          httpResponse.getStatusLine().getStatusCode()

    3.5.2 响应头
          getAllHeaders()/getHeaders(String name)

    3.5.3 响应内容
          HttpEntity httpEntity = httpResponse.getEntity();//此对象包含服务器的响应内容
          String result = EntityUtils.toString(httpEntity);

下面我举一个实例来讲述Android与Java端的数据交互:

   1.这里我使用一个已经封装好的HttpClient对象Post请求

package com.example.jack_and06;

import java.io.Serializable;
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.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 org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;

/**
 * 封装 HttpClient对象POST请求
 *
 */
public class HttpClientPost implements Serializable {

   private static final long serialVersionUID = 1777547416049652217L;

   private static HttpClient httpClient = new DefaultHttpClient();

   static {
      httpClient.getParams().setParameter(
            CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);// 连接时间
      httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
            3000);// 数据传输时间
   }

   // 字符集
   private static String encoding = "UTF-8";

   // 服务器地址+端口号+项目名
   private static String basePath = "http://192.168.43.157:8080/blog_limit/";

   // 子控制器的路径
   private String path;

   // 保存请求中的参数
   private List<NameValuePair> params = new ArrayList<NameValuePair>();;

   public HttpClientPost(String path) {
      super();
      this.path = path;
   }

   /**
    * 向POST请求中添加参数
    *
    * @param name
    * @param value
    */
   public void addParam(String name, String value) {
      if (value == null) {
         params.add(new BasicNameValuePair(name, ""));
      } else {
         params.add(new BasicNameValuePair(name, value));
      }
   }

   /**
    * 提交POST请求
    */
   @SuppressWarnings("unchecked")
   public void submit(final HttpClientPost.Callback callback) {
      /**
       * 调用类对象excute()方法属性
       */
      new AsyncTask() {
         private String json;

         @Override
         protected Object doInBackground(Object... args) {
            try {
               // 1. 创建HttpClient对象

               // 2. 创建HttpGet(或HttpPost)对象
               HttpPost httpPost = new HttpPost(basePath + path);

               // 3. 向POST请求中添加参数(可选)
               if (0 != params.size()) {
                  HttpEntity paramEntity = new UrlEncodedFormEntity(
                        params, encoding);
                  httpPost.setEntity(paramEntity);
               }

               // 4. 发送POST请求,并获得响应
               HttpResponse httpResponse = httpClient.execute(httpPost);

               // 5. 处理响应
               if (200 == httpResponse.getStatusLine().getStatusCode()) {
                  HttpEntity responseEntity = httpResponse.getEntity();// 此对象包含服务器的响应内容
                  this.json = EntityUtils.toString(responseEntity);
               }
            } catch (Exception e) {
               throw new RuntimeException(e);
            }
            return null;
         }

         protected void onPostExecute(Object result) {
            callback.execute(this.json);
         }

      }.execute();
   }
   //创建内部回调函数,使用二十三种设计模式之策略模式  、
   //(作用:在方法或类中已经完成了对应的功能,然后在调用方根据自己的需求去处理结果)
   public static interface Callback {
      void execute(String json);
   }
}

2.创建一个Android布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/bt_main_add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="新增" />

    <Button
        android:id="@+id/bt_main_edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="修改" />

    <Button
        android:id="@+id/bt_main_del"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除" />

    <Button
        android:id="@+id/bt_main_load"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查单个" />

    <Button
        android:id="@+id/bt_main_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查全部" />


</LinearLayout>

3.在Activity类中实现数据的交互 

package com.example.jack_and06;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button bt_main_add;
    private Button bt_main_edit;
    private Button bt_main_del;
    private Button bt_main_load;
    private Button bt_main_list;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //查找控件
        findViews();

        //绑定监听器
        bt_main_add.setOnClickListener(this);
        bt_main_edit.setOnClickListener(this);
        bt_main_del.setOnClickListener(this);
        bt_main_load.setOnClickListener(this);
        bt_main_list.setOnClickListener(this);

    }

    private void findViews() {
        bt_main_add = (Button) findViewById(R.id.bt_main_add);
        bt_main_edit = (Button) findViewById(R.id.bt_main_edit);
        bt_main_del = (Button) findViewById(R.id.bt_main_del);
        bt_main_load = (Button) findViewById(R.id.bt_main_load);
        bt_main_list = (Button) findViewById(R.id.bt_main_list);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_main_add:
                add();
                break;
            case R.id.bt_main_edit:
                edit();
                break;
            case R.id.bt_main_del:
                del();
                break;
            case R.id.bt_main_load:
                load();
                break;
            case R.id.bt_main_list:
                list();
                break;
        }
    }

    private void add() {
        Log.i("test", "add...");
    }

    private void edit() {
        Log.i("test", "edit...");
    }

    private void del() {
        Log.i("test", "del...");
    }

    private void load() {
        Log.i("test", "load...");
    }

    private void list() {
        Log.i("test", "list...");
        //创建httpClientPost对象输入数据路径
        HttpClientPost httpClientPost = new HttpClientPost("userAction.action");
        httpClientPost.addParam("methodName","blogUserList");
        httpClientPost.submit(new HttpClientPost.Callback() {
            @Override
            public void execute(String json) {
                Log.i("json",json);//LogCat输出数据
                ObjectMapper om = new ObjectMapper();
                try {
                    Map<String,Object> map = om.readValue(json, Map.class);
                    List rows = (List) map.get("rows");
                    Map<String,Object> o = (Map<String, Object>) rows.get(0);
                    Log.i("username",o.get("username").toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

 最后我们使用模拟器来查看所查询到的Java数据

 

Android应用在LogCat输出数据信息 

 

猜你喜欢

转载自blog.csdn.net/Giraffe_it/article/details/83344724