遗忘海岸

江湖程序员 -Feiph(LM战士)

导航

Andriod 之数据获取

服务端Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AA.Web.Models
{
    public class ResponseBase
    {
        public int Code { get; set; }
        public string Msg { get; set; }
    }
}
-------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AA.Web.Models
{
    public class LoginResponse:ResponseBase
    {
        public UserInfo User { get; set; }
    }

    public class UserInfo
    {
        public string Username { get; set; }
        public DateTime? AddTime { get; set; }
        public int? Level { get; set; }
        public bool? IsAdmin { get; set; }
        public byte[] Data { get; set; }
    }
}
View Code

 客户端Model

package com.example.aa.model;

public class ResponseBase {
    public int getCode() {
        return Code;
    }
    public void setCode(int code) {
        Code = code;
    }
    public String getMsg() {
        return Msg;
    }
    public void setMsg(String msg) {
        Msg = msg;
    }
    public int Code;
    public String Msg;
}
-------------------
package com.example.aa.model;

public class LoginResponse extends ResponseBase {
    private UserInfo User;

    public UserInfo getUser() {
        return User;
    }

    public void setUser(UserInfo user) {
        User = user;
    }
}
-------------
package com.example.aa.model;

import java.util.Date;

import android.R.bool;

public class UserInfo {

    private Date AddTime;
    private int Level;
    private String Username;
    public Boolean getIsAdmin() {
        return IsAdmin;
    }

    public void setIsAdmin(Boolean isAdmin) {
        IsAdmin = isAdmin;
    }

    public byte[] getData() {
        return Data;
    }

    public void setData(byte[] data) {
        Data = data;
    }

    private Boolean IsAdmin;
    private byte[] Data;
    
    public String getUsername() {
        return Username;
    }

    public void setUsername(String username) {
        Username = username;
    }

    public Date getAddTime() {
        return AddTime;
    }

    public void setAddTime(Date addTime) {
        AddTime = addTime;
    }

    public int getLevel() {
        return Level;
    }

    public void setLevel(int level) {
        Level = level;
    }

}
View Code

说明:如果服务端字段是大写开头的,那么客户端private type Xxxx 也要大写开头
       byte[],json后变成 Data:[1,23...],传输体积变动N备,别拿来传文件

服务端Service

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;
using System.Text;
using System.Collections.Specialized;
using System.Collections;
namespace AA.Web.Controllers
{
    using Models;

    
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Index()
        {
            return View();
        }

        
        public ActionResult AddUser(string username, int level)
        {
            StringBuilder heads = new StringBuilder();
            
            foreach (string  key in HttpContext.Request.Headers.Keys)
            {
                heads.Append(key + ":" + HttpContext.Request.Headers[key] +"$");
            }
            var user = Session["UserInfo"] as UserInfo;
            var msg = user == null ? "未登陆" : user.Username;
            return Content("Msg:" + msg + ",DT:" + DateTime.Now + ",level:" + level + "," + heads.ToString());
        }
        public ActionResult Login(string username, string password)
        {
            LoginResponse response = new LoginResponse();
            List<LoginResponse> list = new List<LoginResponse>();
            try
            {
                
                response.Code = 18;
                response.Msg = "登录成功";
                response.User = new UserInfo() { Username = username, Level = 3, AddTime = DateTime.Now,IsAdmin=true,Data=new byte[]{1,22,33}  };
                
                list.Add(response);
                list.Add(response);
                list.Add(response);
                Session.Add("UserInfo", response.User);
            }
            catch (Exception ex)
            {
                response.Msg = ex.Message;
                response.Code = -1;
               
            }


            return Json(list,"text/json",Encoding.UTF8,JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetUsers()
        {
            List<UserInfo> users = new List<UserInfo>();
            users.Add(new UserInfo() { Username = "张1", Level = 8, AddTime = DateTime.Now,IsAdmin=true,Data=new byte[]{1,22,33} });
            users.Add(new UserInfo() { Username = "张2", Level = 8, AddTime = null, IsAdmin = null, Data = null });
            users.Add(new UserInfo() { Username = "张3", Level = 8, AddTime = DateTime.Now, IsAdmin = true, Data = new byte[] { 1, 22, 33 } });
            users.Add(new UserInfo() { Username = "张4", Level = 8, AddTime = DateTime.Now, IsAdmin = true, Data = new byte[] { 1, 22, 33 } });
            return Json(users, "text/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }

    }
}
View Code

 客户端调用

package com.example.aa;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.R.string;
import android.preference.PreferenceActivity.Header;

public class AccountService {

    //private final static HttpClient httpClient=new DefaultHttpClient();
    
    public static String login(String username, String password) {

        try {
            //"http://192.168.1.7:7086/account/getUsers";//
            String httpUrl = "http://192.168.1.7:7086/Account/login?username=xxx2&password=bbb";
            // HttpGet连接对象
            HttpGet httpRequest = new HttpGet(httpUrl);
            // 取得HttpClient对象
            HttpClient httpClient = new DefaultHttpClient();
            // 请求HttpClient,取得HttpResponse
            HttpResponse httpResponse = httpClient.execute(httpRequest);
            for(org.apache.http.Header h:httpResponse.getAllHeaders()){
                System.out.println(h.getName());
            }
            // 请求成功
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 取得返回的字符串
                String strResult = EntityUtils.toString(httpResponse
                        .getEntity());
                return strResult;
            } else {
                return "";
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    
    public static String addUser(String username, int  level) {

        try {
            String httpUrl ="http://192.168.1.7:7086/account/adduser";
            List<NameValuePair> paramsList=new ArrayList<NameValuePair>();
            paramsList.add(new BasicNameValuePair("username", username));
            paramsList.add(new BasicNameValuePair("level",Integer.toString(level)));
    
            
            // HttpGet连接对象
            HttpPost httpRequest = new HttpPost(httpUrl);
            
            httpRequest.setEntity( new UrlEncodedFormEntity(paramsList, "utf-8") );
            
            // 取得HttpClient对象
            HttpClient httpClient = new DefaultHttpClient();
            // 请求HttpClient,取得HttpResponse
            HttpResponse httpResponse = httpClient.execute(httpRequest);
            for(org.apache.http.Header h:httpResponse.getAllHeaders()){
                System.out.println(h.getName());
            }
            // 请求成功
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 取得返回的字符串
            
                String strResult = EntityUtils.toString(httpResponse
                        .getEntity());
                return strResult;
            } else {
                return "";
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
View Code
package com.example.aa;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;

import org.apache.http.HttpRequest;
import org.json.JSONArray;

import com.example.aa.model.LoginResponse;
import com.example.aa.model.UserInfo;
import com.example.aa.util.GsonUtil;
import com.example.aa.util.SystemUiHider;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


import android.R.bool;
import android.R.integer;
import android.R.string;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class FullscreenActivity extends Activity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * If set, will toggle the system UI visibility upon interaction. Otherwise,
     * will show the system UI visibility upon interaction.
     */
    private static final boolean TOGGLE_ON_CLICK = true;

    /**
     * The flags to pass to {@link SystemUiHider#getInstance}.
     */
    private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

    /**
     * The instance of the {@link SystemUiHider} for this activity.
     */
    private SystemUiHider mSystemUiHider;
    private boolean isFirest=true;
    private void showDialog(String msg){
          Dialog alertDialog = new AlertDialog.Builder(FullscreenActivity.this). 
                    setTitle("信息"). 
                    setIcon(R.drawable.ic_launcher). 
                    setMessage(msg).
                    create(); 
            alertDialog.show(); 
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_fullscreen);

        final View controlsView = findViewById(R.id.fullscreen_content_controls);
        final View contentView = findViewById(R.id.fullscreen_content);
        //============Start My============
        
        
        
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
         

        
        final Button btn1=(Button) findViewById(R.id.button1);
        final Button btnPost=(Button)findViewById(R.id.button2);  
        final EditText txtTips=(EditText)findViewById(R.id.editText1);
        btn1.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                
                //et1.setText("NND你点了");
                 try {
                      String json=AccountService.login("xxx", "123");
                      JSONArray jsonArray=new JSONArray(json);
                      Gson gson=GsonUtil.getGson();
                      Type listType =  new TypeToken<ArrayList<LoginResponse>>(){}.getType();
                      ArrayList<LoginResponse> users=gson.fromJson(json,  listType);
                      showDialog(users.get(0).getUser().getUsername());
                } catch (Exception e) {
                    showDialog(e.getMessage());
                }
            
            
            }
        });
        
        btnPost.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                try{
                    if(isFirest)
                    {
                      AccountService.login("Admin", "xxx");
                     isFirest=false;
                    }
                    String retString=AccountService.addUser("张老三他外甥的的小固执", 8);
                    txtTips.setText(retString);
                }catch (Exception e) {
                    showDialog(e.getMessage());
                }
                
            }
        });
        
        
        
        
        
        //==============End My==================
        
        // Set up an instance of SystemUiHider to control the system UI for
        // this activity.
        mSystemUiHider = SystemUiHider.getInstance(this, contentView,
                HIDER_FLAGS);
        mSystemUiHider.setup();
        mSystemUiHider
                .setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
                    // Cached values.
                    int mControlsHeight;
                    int mShortAnimTime;

                    @Override
                    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
                    public void onVisibilityChange(boolean visible) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
                            // If the ViewPropertyAnimator API is available
                            // (Honeycomb MR2 and later), use it to animate the
                            // in-layout UI controls at the bottom of the
                            // screen.
                            if (mControlsHeight == 0) {
                                mControlsHeight = controlsView.getHeight();
                            }
                            if (mShortAnimTime == 0) {
                                mShortAnimTime = getResources().getInteger(
                                        android.R.integer.config_shortAnimTime);
                            }
                            controlsView
                                    .animate()
                                    .translationY(visible ? 0 : mControlsHeight)
                                    .setDuration(mShortAnimTime);
                        } else {
                            // If the ViewPropertyAnimator APIs aren't
                            // available, simply show or hide the in-layout UI
                            // controls.
                            controlsView.setVisibility(visible ? View.VISIBLE
                                    : View.GONE);
                        }

                        if (visible && AUTO_HIDE) {
                            // Schedule a hide().
                            delayedHide(AUTO_HIDE_DELAY_MILLIS);
                        }
                    }
                });

        // Set up the user interaction to manually show or hide the system UI.
        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TOGGLE_ON_CLICK) {
                    mSystemUiHider.toggle();
                } else {
                    mSystemUiHider.show();
                }
            }
        });

        // Upon interacting with UI controls, delay any scheduled hide()
        // operations to prevent the jarring behavior of controls going away
        // while interacting with the UI.
//        findViewById(R.id.dummy_button).setOnTouchListener(
//                mDelayHideTouchListener);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };

    Handler mHideHandler = new Handler();
    Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            mSystemUiHider.hide();
        }
    };

    /**
     * Schedules a call to hide() in [delay] milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
}
View Code
package com.example.aa.util;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.R.string;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class DateDeserializer implements JsonDeserializer<Date> {

    @Override
     public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException 
     { 
     String JSONDateToMilliseconds = "/Date\\((.*?)\\)/"; 
     Pattern pattern = Pattern.compile(JSONDateToMilliseconds);
     String value=json.getAsJsonPrimitive().getAsString();
     Matcher matcher = pattern.matcher(value);
     String result = matcher.replaceAll("$1");

     return new Date(new Long(result));
 }
}
View Code
package com.example.aa.util;

import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonUtil {
  public static Gson getGson(){
      GsonBuilder gsonb = new GsonBuilder();
      DateDeserializer ds = new DateDeserializer(); 
      gsonb.registerTypeAdapter(Date.class, ds); 
      Gson gson = gsonb.create();
      return gson;

  }
}
View Code

 说明:asp.net mvc的Data json需要特别处理下

 

服务端反Json序列化
            JavaScriptSerializer jss = new JavaScriptSerializer();
            var list= jss.Deserialize<List<LoginResponse>>(jsonData);
            list.ForEach(ent => ent.Msg = "卡看看");
            return Json(list, "text/json", Encoding.UTF8);

posted on 2013-08-15 15:53  遗忘海岸  阅读(1114)  评论(0编辑  收藏  举报