服务端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. streamsets microservice pipeline 试用

    实际上还是一个pipeline,只是添加了一些规则以及内嵌的http server 方便我们对于基于http 或者类似轻量 协议数据的处理 基本环境 使用docker&& docker ...

  2. java的static研究

    (1)static关键字:可以用于修饰属性.方法和类. 1,属性:无论一个类生成了多少个对象,所有这些对象共同使用唯一的一份静态的成员变量(不能修饰临时变量 2,方法:static修饰的方法叫做静态, ...

  3. TimeExit 界面无点击定时退出类

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.W ...

  4. git push 免密码

    git push 免密码 通用情况 使用ssh协议 git add 使用tab键自动补全的中文文件名乱码 jupyter notebook 创建密码 git push 免密码 通用情况 1.使用文件创 ...

  5. oracle 归档日志总结

    Oracle 归档模式和非归档模式 归档模式和非归档模式 在DBA部署数据库之初,必须要做出的最重要决定之一就是选择归档模式(ARCHIVELOG)或者非 归档模式(NOARCHIVELOG )下运行 ...

  6. mysql中去重 distinct 用法

    在使用MySQL时,有时需要查询出某个字段不重复的记录,这时可以使用mysql提供的distinct这个关键字来过滤重复的记录,但是实际中我们往往用distinct来返回不重复字段的条数(count( ...

  7. java Long

    1. Long.valueOf(b) 返回的是对象 public static Long valueOf(String s) throws NumberFormatException { )); } ...

  8. WebDriverException: Message: 'phantomjs.exe' executable needs to be in PATH.

    本文转载自:http://blog.csdn.net/sinat_36764186/article/details/55520444 网上的某测试代码: from selenium import we ...

  9. 32位汇编基础_内存_每个应用进程都会有自己独立的4GB内存空间

    1.每个应用进程都会有自己独立的4GB内存空间 这句话很多人听起来可能会很矛盾很不解. 例如,我的电脑只有2GB的内存,打开个软件机会占用4GB内存,而我的电脑内存只有2GB,显然不够用,但是为什么程 ...

  10. 关于jQuery的$.proxy()应用.

    今天在看<<锋利的jQuery>>时看到了proxy()的使用,感觉很模糊,就到处找资料. jQuery的源码也没看明白. 不过总算明白了proxy的用法了; <inpu ...