Android 中传递 json 的问题

原问题来自于CSDN问答频道,更多解决方案见:http://ask.csdn.net/questions/2520

问题描述:

我在开发一个程序,在 webpage 上使用jquery。

$.post(url, {param: paramstring}, function(result){});

根据参数结构,Paramstring 是一个 json字符串,如:{"action":"get","username":"username"}
现在我想在android中运行,再在页面上添加两个textview 来输入用户名和密码。也有一个注册按钮。按钮监听程序:

EditText et1 = (EditText)findViewById(R.id.username);
String user = et1.getText().toString();
EditText et2 = (EditText)findViewById(R.id.pass);
String password = et2.getText().toString();
// the password should upload after MD5 encryption. this is encryption method. the result is the same with js encryption.
String password_md5 = toMd5(password.getBytes());   
Log.d(TAG, user+"-"+password+"-"+password_md5);
try {
HttpPost request = new HttpPost(URL);
JSONObject params = new JSONObject();
params.put("action", "get");
params.put("result", "user");
params.put("category", "base");
params.put("username", user);
params.put("password", password_md5);

List<BasicNameValuePair> sendData = new ArrayList<BasicNameValuePair>();
sendData.add(new BasicNameValuePair("param", params.toString()));

System.out.println(params.toString());

request.setEntity(new UrlEncodedFormEntity(sendData,"utf-8"));
System.out.println(EntityUtils.toString(request.getEntity()));

HttpResponse response= new DefaultHttpClient().execute(request);
String retSrc = EntityUtils.toString(response.getEntity()); 

System.out.println(retSrc);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 


上面的代码返回数据显示登录错误,我觉得是因为 json 结构的问题。{param:paramstr} in $.post()方法是一个map。我改了好几次还是错误的。
什么问题呢?

解决方案:

你应该分别传递每个参数,不需要一个 json 结构。 jQuery 使用的 JSON 结构只是 $.post() 方法中一个可变数目的参数。
把你代码中的这部分:

params.put("action", "get");
params.put("result", "user");
params.put("category", "base");
params.put("username", user);
params.put("password", password_md5);

List<BasicNameValuePair> sendData = new ArrayList<BasicNameValuePair>();
sendData.add(new BasicNameValuePair("param", params.toString()));


改为:

List<BasicNameValuePair> sendData = new ArrayList<BasicNameValuePair>();
sendData.add(new BasicNameValuePair("action", "get"));
sendData.add(new BasicNameValuePair("result", "user"));
sendData.add(new BasicNameValuePair("category", "base"));
sendData.add(new BasicNameValuePair("username", user));
sendData.add(new BasicNameValuePair("password", password_md5));


用sendData list 取代 JSON 对象。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值