// 设置Post服务器的参数,即json对象,并返回该对象。
public static JSONObject setPostPara(Activity activity){
// 获取参数值省略 (imei等参数的获取) 其它的代码也省略了部分
JSONObject params = new JSONObject();
try {
params.put("IMEI", imei);
params.put("IMSI", imsi);
params.put("MAC", mac);
// ...
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("", "apple-params=" + params);
return params;
}
客户端访问服务器:将一个json对象post到服务器的指定网址,从服务器返回值json对象中获取所需值。
// 判断用户的抽奖权限 以及中奖概率。
// 客户端请求格式:{“IMEI“: “XXXX “, “IMSI“: “XXXXX “, “MAC“: “XXXX “, ...}
// 服务端返回格式:{"UserEnabled":-1,"Probability":'[10,0,20,30,0,0]'}
public static JSONObject setActivity(Activity context) {
// 第一步,创建HttpPost对象
String url = "http://apk...";
HttpPost httpPost = new HttpPost(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
JSONObject resJson = new JSONObject();
// 第二步,设置HTTP POST请求参数, 使用json对象
JSONObject jsonParam = setPostPara(context);
StringEntity entity;
try {
entity = new StringEntity(jsonParam.toString(),"utf-8"); // 解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
// 发起请求
HttpResponse httpResponse = httpClient.execute(httpPost);
// 请求结束,返回结果。并解析json。
String resData = EntityUtils.toString(httpResponse.getEntity());
resJson = new JSONObject(resData);
Log.i("","apple-Activity-json=" + resJson + "ActivityEnabled=" + resJson.get("ActivityEnabled") + "Probability=" + resJson.getJSONArray("Probability"));
// 省略了一堆的catch(上面不少函数需捕捉异常)
} catch (JSONException e) {
e.printStackTrace();
}
return resJson;
}