.Net程序员安卓学习之路3:Post数据给网络API

本例我们实现一次真正的网络交互,将数据POST到API,然后接收服务器的返回值进行处理,同时引入自定义类型和传说中阿里的FastJson。

实现思路如:

1. 在API端接收客户POST的数据还原成对象,给每个属性加个后缀后输出;

2. 在客户端输入用户名和密码,用来和服务器端返回的进行对比;

我们POST给服务器的是name=mady&pwd=123,服务器分别加了后缀为name=madya

&pwd=1231所以我们客户端需要输入madya和1231才能验证成功。

具体操作展示如下:

wps3BD7.tmp

wps3BD8.tmp

一、准备API:

目前写API使用ASP.NET WEB API2再合适不过了。在VS2013中创建一个API项目,先配置他支持JSON:

打开项目中的WebApiConfig文件,在Register方法中加入一个配置项:

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

创建实体类如:

    public class UserInfo
    {
        public string name { get; set; }
        public string pwd { get; set; }
    }

打开ValuesController修改代码如下:

        // POST api/values
        public UserInfo Post([FromBody]UserInfo value)
        {
            return new UserInfo { name = value.name + "a", pwd = value.pwd+"1" };
        }

就可以打开Fidder调试了,直到成功为止:

wps3BE9.tmp

 

二、引入阿里的FastJson包

直接右键粘贴进去即可:

wps3BFA.tmp

这个包真心好使:

String json=JSON.toJSONString(user);     //序列化 
UserInfo userInfo=JSON.parseObject(json,UserInfo.class);    //反序列化

就这2句话全部搞定。

我们继续,先新建一个Java的实体类:

import java.io.Serializable;

public class UserInfo implements Serializable{
private String name;
private String pwd;

public String getPwd() 
{
    return pwd;
}

public void setPwd(String pwd) 
{
    this.pwd = pwd;
}

public String getName() 
{
    return name;
}

public void setName(String name) 
{
    this.name = name;
}

}

然后修改网络访问类,上节那个太简陋了(见附)。

然后修改异步部分代码:

        protected String doInBackground(String... params)
        {
//            String citiesString ="{\"name\":\"mady\",\"pwd\":123}"; 
            UserInfo user=new UserInfo();
            user.setName("mady");
            user.setPwd("123");
            
            String str_json=JSON.toJSONString(user);  
            return HttpUtils.sendPostMessage(params[0],str_json);
        }

和完成代码:

        protected void onPostExecute(String result)
        {
            TextView lblInfo=(TextView)findViewById(R.id.form_title);
            EditText txt_login_name=(EditText)findViewById(R.id.txt_login_name);
            EditText txt_login_pass=(EditText)findViewById(R.id.txt_login_pwd);
            String loginName=txt_login_name.getText().toString().trim();
            String loginPass=txt_login_pass.getText().toString().trim();
            
            UserInfo userInfo=JSON.parseObject(result,UserInfo.class); 
            if(loginPass.equals(userInfo.getPwd())&&loginName.equals(userInfo.getName()))
            {
                lblInfo.setText("登录成功!");
            }
            else
            {
                lblInfo.setText("登录失败!");
            }
          }

到此完工,没有修改的就是没有变化的。

附上新网络访问类:

public class HttpUtils
{
    /**
     * @param path    请求的服务器URL地址
     * @param encode    编码格式
     * @return    将服务器端返回的数据转换成String
     */
    public static String sendPostMessage(String path,String jsonStr)
    {
        String result = "";
        HttpClient httpClient = new DefaultHttpClient();
        try
        {
            HttpPost httpPost = new HttpPost(path);
            httpPost.addHeader("content-type","text/json");

        httpPost.setEntity(new StringEntity(jsonStr));     
            HttpResponse httpResponse = httpClient.execute(httpPost);

            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
//                Log.e("Json+++++2:", jsonStr);    log info for debug
                HttpEntity httpEntity = httpResponse.getEntity();
                if(httpEntity != null)
                {
                    result = EntityUtils.toString(httpEntity, "UTF-8");
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            httpClient.getConnectionManager().shutdown();
        }
        
        return result;
    }
}

 

posted @ 2015-02-09 22:35  石曼迪  Views(908)  Comments(0Edit  收藏  举报
瓴域建设-环保事业中心