服务端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; }
}
}

客户端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;
} }

说明:如果服务端字段是大写开头的,那么客户端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 = ;
response.Msg = "登录成功";
response.User = new UserInfo() { Username = username, Level = , AddTime = DateTime.Now,IsAdmin=true,Data=new byte[]{,,} }; list.Add(response);
list.Add(response);
list.Add(response);
Session.Add("UserInfo", response.User);
}
catch (Exception ex)
{
response.Msg = ex.Message;
response.Code = -; } 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 = , AddTime = DateTime.Now,IsAdmin=true,Data=new byte[]{,,} });
users.Add(new UserInfo() { Username = "张2", Level = , AddTime = null, IsAdmin = null, Data = null });
users.Add(new UserInfo() { Username = "张3", Level = , AddTime = DateTime.Now, IsAdmin = true, Data = new byte[] { , , } });
users.Add(new UserInfo() { Username = "张4", Level = , AddTime = DateTime.Now, IsAdmin = true, Data = new byte[] { , , } });
return Json(users, "text/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
} }
}

客户端调用

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);
}
}
}
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 = ; /**
* 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 > ) {
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", "");
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().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("张老三他外甥的的小固执", );
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 == ) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == ) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? : 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();
} /**
* 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);
}
}
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));
}
}
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; }
}

说明: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);

Andriod 之数据获取的更多相关文章

  1. Andriod 自定义控件之创建可以复用的组合控件

    前面已学习了一种自定义控件的实现,是Andriod 自定义控件之音频条,还没学习的同学可以学习下,学习了的同学也要去温习下,一定要自己完全的掌握了,再继续学习,贪多嚼不烂可不是好的学习方法,我们争取学 ...

  2. Web Api 与 Andriod 接口对接开发经验

    最近一直急着在负责弄Asp.Net Web Api 与 Andriod 接口开发的对接工作! 刚听说要用Asp.Net Web Api去跟 Andriod 那端做接口对接工作,自己也是第一次接触Web ...

  3. Andriod小项目——在线音乐播放器

    转载自: http://blog.csdn.net/sunkes/article/details/51189189 Andriod小项目——在线音乐播放器 Android在线音乐播放器 从大一开始就已 ...

  4. Andriod学习笔记1:代码优化总结1

    多行变一行 比如说开发一个简单的计算器应用程序,需要定义0-9的数字按钮,第一次就习惯性地写出了如下代码: Button btn0; Button btn1; Button btn2; Button ...

  5. 20160113第一个ANDRIOD开发日志

    今天开发了第一个andriod程序,测试录音和播放功能.源码是网上抄来的. 代码: unit Unit2; interface uses   System.SysUtils, System.Types ...

  6. 0.[WP Developer体验Andriod开发]之从零安装配置Android Studio并编写第一个Android App

    0. 所需的安装文件 笔者做了几年WP,近来对Android有点兴趣,尝试一下Android开发,废话不多说,直接进入主题,先安装开发环境,笔者的系统环境为windows8.1&x64. 安装 ...

  7. Andriod Studio adb.exe,start-server' failed -- run manually if necessary 解决

    首先查看了我的任务管理器,共有三个adb的程序在运行: 错误提示的是 Andriod Studio 中的adb.exe启动失败,于是,去关掉另外两个adb.exe,两分钟左右后,又出现了三个adb. ...

  8. 数据获取以及处理Beta版本展示

    产品描述 这个产品的目的是为了学霸网站提供后台数据获取以及处理操作.在alpha阶段基本调通的基础至上,我们希望在bate版本中加入对于问答对的处理,图片的获取等功能. 预期目标 在alpha阶段,我 ...

  9. [Andriod] - Andriod Studio + 逍遥模拟器

    Andriod Studio自身自带的模拟器实在太卡,用Genymotion模拟器又要安装VirtualBox,然后一堆的设置,结果还是卡B. 网上下了个逍遥模拟器,这模拟器是游戏专用的,目前正式版的 ...

随机推荐

  1. centos7上docker安装和使用教程

    Docker 是一个创建和管理 Linux 容器的开源工具.容器就像是轻量级的虚拟机,并且可以以毫秒级的速度来启动或停止.Docker 帮助系统管理员和程序员在容器中开发应用程序,并且可以扩展到成千上 ...

  2. ivy antlib shemalocation

    <?xml version="1.0" encoding="UTF-8"?> <project name="yourproject& ...

  3. Java反射机制的适用场景及其利与弊 ***

    一.反射的适用场景是什么? 1).Java的反射机制在做基础框架的时候非常有用,有一句话这么说来着:反射机制是很多Java框架的基石.而一般应用层面很少用,不过这种东西,现在很多开源框架基本都已经给你 ...

  4. ajax readyState=4并且status=200时,还进error方法

    今天在使用jQuery.ajax方法去调用后台方法时,ajax中得参数data类型是"JSON",后台DEBUG调试,运行正常, 返回正常的结果集,但是前端一直都进到ajax的er ...

  5. (转)Flex开发工具Flex Builder 3 下载及注册码

    本文转载自:http://blog.csdn.net/wlxtaking/article/details/5779762 Flex是通过java或者.net等非Flash途径,解释.mxml文件组织c ...

  6. c语言个人财务管理系统

    这个是我的一个网上朋友写的,仅供大家参考: 在这里留个记录 #include<stdio.h>#include<string.h>#define null 0#define m ...

  7. Carrying per-request context using the HttpRequestMessage.Properties

    In a Web API application, I use Castle Windsor to supply services configured with PerWebRequest life ...

  8. 修改jvm xms参数

    http://hi.baidu.com/200770842223/item/9358aad4f3194e1a20e2501b http://www.cnblogs.com/mingforyou/arc ...

  9. hadoop学习day1环境配置笔记(非完整流程)

    hdfs的工作机制: 1.客户把一个文件存入hdfs,其实hdfs会把这个文件切块后,分散存储在N台linux机器系统中(负责存储文件块的角色:data node)<准确来说:切块的行为是由客户 ...

  10. Servlet类源码说明

    servlet是学习java web不可不懂的一个类,网上各种教程都参杂太多,每次理解都感觉像把别人吐出来的食物再放在嘴里咀嚼,小编一怒之下,直接打开源码,原汁原味的芬芳扑面而来: /** * Def ...