标签:
http://www.23code.com/tu-biao-chart/
从无到有,从来没有接触过Json,以及与服务器的交互。然后慢慢的熟悉,了解了一点。把我学到的东西简单的做个总结,也做个记录,万一以后用到,就不用到处找了。
主要是简单的数据交互,就是字符串的交互,传数据,取数据。刚开始用的普通方法,后来研究了下xUtils框架。
服务器端有人开发,这一块不是我负责,所以我只负责客户端传数据以及接受数据后的处理就OK了。
传递数据的形式,主要是看服务端的接口怎么写,服务器是接受JSON字符串,还是要form表单格式(我认为form表单格式就是键值对)。
xUtils:
不需要关联library,就下载jar包,复制到libs下就可以了,这是下载地址:http://download.csdn.net/detail/u012975370/9003713
还有就是,你如果想使用library到自己的项目下,注意一点主项目文件和library库文件,必须在同一个文件夹目录下,否则运行项目是报错的
http://blog.csdn.net/dj0379/article/details/38356773
项目原码地址:https://github.com/wyouflf/xUtils
http://www.gbtags.com/gb/share/4360.htm
Volley:
初识Volley的基本用法:http://www.apihome.cn/view-detail-70211.html
使用Volley加载网络图片:http://www.apihome.cn/view-detail-70212.html
定制自己的Request:http://www.apihome.cn/view-detail-70213.html
还有一些框架:KJFeame和Afinal
KJFrame:
http://git.oschina.net/kymjs/KJFrameForAndroid
http://www.codeceo.com/article/Android-orm-kjframeforandroid.html
1.要发送到服务器端的是以JSON字符串的形式发送的。(下面的格式)
- {"device":"hwG620S-UL00","brand":"HUAWEI","model":"G620S-UL00","imei":"865242025001258","romversion":"G620S-UL00V100R001C17B264"}
- private void sendData1() {
- new Thread(new Runnable() {
- @Override
- public void run() {
- Log.i(TEST_TAG, "2222");
- try {
-
- HttpPost post = new HttpPost(ACTIVATE_PATH);
-
- JSONObject param = new JSONObject();
- param.put("romversion", serviceInfoMap.get("romversion"));
- param.put("brand", serviceInfoMap.get("brand"));
- param.put("model", serviceInfoMap.get("model"));
- param.put("device", serviceInfoMap.get("device"));
- param.put("imei", serviceInfoMap.get("imei"));
-
- StringEntity se = new StringEntity(param.toString(),
- "utf-8");
- post.setEntity(se);
- Log.i(TEST_TAG, "JSON为---> " + param.toString());
-
-
-
-
- HttpParams params = new BasicHttpParams();
- DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(
- params);
- localDefaultHttpClient.getParams().setParameter(
- "http.connection.timeout", Integer.valueOf(30000));
- localDefaultHttpClient.getParams().setParameter(
- "http.socket.timeout", Integer.valueOf(30000));
- HttpResponse response = localDefaultHttpClient
- .execute(post);
-
- String retStr = EntityUtils.toString(response.getEntity());
-
- JSONObject result = new JSONObject(retStr);
- int status_value = response.getStatusLine().getStatusCode();
- Log.i(TEST_TAG, "" + status_value);
- String statusValue = "";
- statusValue = result.getString("status");
- Log.i(TEST_TAG, statusValue);
- if (!statusValue.equals("")) {
-
- mHandler.sendEmptyMessage(CLOSE_DIALOG);
-
-
- if (Integer.parseInt(statusValue) == 1) {
- mHandler.sendEmptyMessage(SHOW_SUCCESS);
-
- Settings.System.putInt(getContentResolver(),
- SETTING_MODIFY_NAME, 1);
- } else {
- mHandler.sendEmptyMessage(SHOW_FAILURE);
- }
- }
-
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- mHandler.sendEmptyMessage(CONTENT_STATUS);
- } catch (SocketException e) {
- mHandler.sendEmptyMessage(CONTENT_STATUS);
- } catch (IOException e) {
- mHandler.sendEmptyMessage(CONTENT_STATUS);
- e.printStackTrace();
- } catch (JSONException e) {
- mHandler.sendEmptyMessage(CONTENT_STATUS);
- e.printStackTrace();
- }
- }
- }).start();
- }
2.以form表单的格式发送到服务端
将传递的数据打印出来,格式是这样的,和json串是不一样的。[romversion=G620S-UL00V100R001C17B264, brand=HUAWEI, model=G620S-UL00, device=hwG620S-UL00, imei=865242024756522]
- private void sendData1() {
- new Thread(new Runnable() {
- @Override
- public void run() {
- Log.i(TEST_TAG, "2222");
- try {
-
- HttpPost post = new HttpPost(ACTIVATE_PATH);
-
- List<NameValuePair> paramsForm = new ArrayList<NameValuePair>();
- paramsForm.add(new BasicNameValuePair("romversion",
- serviceInfoMap.get("romversion")));
- paramsForm.add(new BasicNameValuePair("brand",
- serviceInfoMap.get("brand")));
- paramsForm.add(new BasicNameValuePair("model",
- serviceInfoMap.get("model")));
- paramsForm.add(new BasicNameValuePair("device",
- serviceInfoMap.get("device")));
- paramsForm.add(new BasicNameValuePair("imei",
- serviceInfoMap.get("imei")));
- Log.i(TEST_TAG, paramsForm.toString());
- post.setEntity(new UrlEncodedFormEntity(paramsForm,
- HTTP.UTF_8));
-
-
- HttpParams params = new BasicHttpParams();
- DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(
- params);
- localDefaultHttpClient.getParams().setParameter(
- "http.connection.timeout", Integer.valueOf(30000));
- localDefaultHttpClient.getParams().setParameter(
- "http.socket.timeout", Integer.valueOf(30000));
- HttpResponse response = localDefaultHttpClient
- .execute(post);
-
- String retStr = EntityUtils.toString(response.getEntity());
-
- JSONObject result = new JSONObject(retStr);
- int status_value = response.getStatusLine().getStatusCode();
- Log.i(TEST_TAG, "" + status_value);
- String statusValue = "";
- statusValue = result.getString("status");
- Log.i(TEST_TAG, "status: " + statusValue);
- Log.i(TEST_TAG, "datatime: " + result.getString("datatime"));
- Log.i(TEST_TAG, "message: " + result.getString("message"));
- if (!statusValue.equals("")) {
-
- mHandler.sendEmptyMessage(CLOSE_DIALOG);
-
-
- if (Integer.parseInt(statusValue) == 1) {
-
- Settings.System.putInt(getContentResolver(),
- SETTING_MODIFY_NAME, 1);
- mHandler.sendEmptyMessage(SHOW_SUCCESS);
- } else {
- mHandler.sendEmptyMessage(SHOW_FAILURE);
- }
- }
-
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- mHandler.sendEmptyMessage(SHOW_FAILURE);
- mHandler.sendEmptyMessage(CONTENT_STATUS);
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- mHandler.sendEmptyMessage(SHOW_FAILURE);
- mHandler.sendEmptyMessage(CONTENT_STATUS);
- } catch (SocketException e) {
- mHandler.sendEmptyMessage(SHOW_FAILURE);
- mHandler.sendEmptyMessage(CONTENT_STATUS);
- } catch (IOException e) {
- mHandler.sendEmptyMessage(SHOW_FAILURE);
- mHandler.sendEmptyMessage(CONTENT_STATUS);
- e.printStackTrace();
- } catch (JSONException e) {
- mHandler.sendEmptyMessage(SHOW_FAILURE);
- mHandler.sendEmptyMessage(CONTENT_STATUS);
- e.printStackTrace();
- }
- }
- }).start();
- }
3.xUtils框架的post上传数据,表单格式
- private void xUtilsFrame() {
- RequestParams params = new RequestParams();
- params.addBodyParameter("romversion", serviceInfoMap.get("romversion"));
- params.addBodyParameter("brand", serviceInfoMap.get("brand"));
- params.addBodyParameter("model", serviceInfoMap.get("model"));
- params.addBodyParameter("device", serviceInfoMap.get("device"));
- params.addBodyParameter("imei", serviceInfoMap.get("imei"));
- Log.i(TEST_TAG, params.getEntity().toString());
-
- HttpUtils http = new HttpUtils();
- http.configCurrentHttpCacheExpiry(1000 * 10);
- http.send(HttpMethod.POST, ACTIVATE_PATH, params,
- new RequestCallBack<String>() {
-
- @Override
- public void onSuccess(ResponseInfo<String> responseInfo) {
- Log.i(TEST_TAG, "接收到的结果为---》" + responseInfo.result);
- Log.i(TEST_TAG, "请求码为--->" + responseInfo.statusCode);
- try {
- JSONObject jsonObject = new JSONObject(
- responseInfo.result);
- Log.i(TEST_TAG, jsonObject.getString("message"));
- if (jsonObject.getString("status").equals("1")) {
- mHandler.sendEmptyMessage(CLOSE_DIALOG);
- mHandler.sendEmptyMessage(SHOW_SUCCESS);
- Settings.System.putInt(getContentResolver(),
- SETTING_MODIFY_NAME, 1);
- } else {
- mHandler.sendEmptyMessage(CLOSE_DIALOG);
- mHandler.sendEmptyMessage(SHOW_FAILURE);
- }
- } catch (JSONException e) {
-
- e.printStackTrace();
- }
- }
-
- @Override
- public void onFailure(HttpException error, String msg) {
- Toast.makeText(getApplicationContext(), "失败了",
- Toast.LENGTH_LONG).show();
- }
- });
- }
4.xUtils框架,json数据格式
- private void xUtilsFrame2() {
- try {
- RequestParams params = new RequestParams();
-
- JSONObject param = new JSONObject();
- param.put("romversion", serviceInfoMap.get("romversion"));
- param.put("brand", serviceInfoMap.get("brand"));
- param.put("model", serviceInfoMap.get("model"));
- param.put("device", serviceInfoMap.get("device"));
- param.put("imei", serviceInfoMap.get("imei"));
- StringEntity sEntity = new StringEntity(param.toString(), "utf-8");
- params.setBodyEntity(sEntity);
- Log.i(TEST_TAG, "params-->" + params.toString());
- Log.i(TEST_TAG, "param-->" + param.toString());
- Log.i(TEST_TAG, "param-entity-->" + sEntity.toString());
-
- HttpUtils http = new HttpUtils();
- http.configCurrentHttpCacheExpiry(1000 * 10);
- http.send(HttpMethod.POST, ACTIVATE_PATH, params,
- new RequestCallBack<String>() {
-
- @Override
- public void onSuccess(ResponseInfo<String> responseInfo) {
- Log.i(TEST_TAG, "接收到的结果为---》" + responseInfo.result);
- Log.i(TEST_TAG, "请求码为--->"
- + responseInfo.statusCode);
- try {
- JSONObject jsonObject = new JSONObject(
- responseInfo.result);
- Log.i(TEST_TAG, jsonObject.getString("message"));
- if (jsonObject.getString("status").equals("1")) {
- mHandler.sendEmptyMessage(CLOSE_DIALOG);
- mHandler.sendEmptyMessage(SHOW_SUCCESS);
- Settings.System.putInt(
- getContentResolver(),
- SETTING_MODIFY_NAME, 1);
- } else {
- mHandler.sendEmptyMessage(CLOSE_DIALOG);
- mHandler.sendEmptyMessage(SHOW_FAILURE);
- }
- } catch (JSONException e) {
-
- e.printStackTrace();
- }
- }
-
- @Override
- public void onFailure(HttpException error, String msg) {
- Toast.makeText(getApplicationContext(), "失败了",
- Toast.LENGTH_LONG).show();
- }
- });
-
- } catch (JSONException e1) {
-
- e1.printStackTrace();
- } catch (UnsupportedEncodingException e) {
-
- e.printStackTrace();
- }
- }
5.Volley框架:StringRequest,from表单
- private void volleyFrameSR() {
-
- final RequestQueue mQueue = Volley.newRequestQueue(this);
-
- StringRequest stringRequest = new StringRequest(Method.POST,
- ACTIVATE_PATH, new Response.Listener<String>() {
-
- @Override
- public void onResponse(String response) {
- Log.i(TEST_TAG, "返回结果为--->" + response);
- try {
- JSONObject jsonObject = new JSONObject(response);
- Log.i(TEST_TAG,
- "status-->"
- + jsonObject.getString("status"));
- Log.i(TEST_TAG,
- "message-->"
- + jsonObject.getString("message"));
- mQueue.cancelAll("StringRequest");
- mHandler.sendEmptyMessage(SHOW_SUCCESS);
- mHandler.sendEmptyMessage(CLOSE_DIALOG);
- } catch (JSONException e) {
-
- e.printStackTrace();
- }
- }
-
- }, new Response.ErrorListener() {
-
- @Override
- public void onErrorResponse(VolleyError error) {
- Log.e(TEST_TAG, error.getMessage(), error);
- mHandler.sendEmptyMessage(SHOW_FAILURE);
- }
- }) {
-
- @Override
- protected Map<String, String> getParams() throws AuthFailureError {
- Map<String, String> map = new HashMap<String, String>();
- map.put("romversion", serviceInfoMap.get("romversion"));
- map.put("brand", serviceInfoMap.get("brand"));
- map.put("model", serviceInfoMap.get("model"));
- map.put("device", serviceInfoMap.get("device"));
- map.put("imei", serviceInfoMap.get("imei"));
- Log.i(TEST_TAG, "发送结果为--->" + map.toString());
-
-
-
-
- return map;
- }
- };
- stringRequest.setTag("StringRequest");
-
- mQueue.add(stringRequest);
- }
这个写了太多的代码,这是方法的原型:
- StringRequest stringRequest = new StringRequest(Method.POST, url, listener, errorListener) {
- @Override
- protected Map<String, String> getParams() throws AuthFailureError {
- Map<String, String> map = new HashMap<String, String>();
- map.put("params1", "value1");
- map.put("params2", "value2");
- return map;
- }
- };
根据我服务器的接受模式,我觉得他发送的结果是form表单格式
6.Volley框架: JsonObjectRequest。
因为它的方法中传递的的请求参数为JsonObject,目前还没有找到传递form格式的方法。
- private void volleyFrameJR() {
-
- final RequestQueue mQueue = Volley.newRequestQueue(this);
-
- JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
- Method.POST, ACTIVATE_PATH, null,
- new Response.Listener<JSONObject>() {
-
- @Override
- public void onResponse(JSONObject response) {
- Log.i(TEST_TAG, "返回结果为--->" + response.toString());
- try {
-
- Log.i(TEST_TAG,
- "status-->" + response.getString("status"));
- Log.i(TEST_TAG,
- "message-->"
- + response.getString("message"));
- mHandler.sendEmptyMessage(SHOW_SUCCESS);
- mHandler.sendEmptyMessage(CLOSE_DIALOG);
- } catch (JSONException e) {
-
- e.printStackTrace();
- }
- }
- }, new Response.ErrorListener() {
-
- @Override
- public void onErrorResponse(VolleyError error) {
- Log.e(TEST_TAG, error.getMessage(), error);
- mHandler.sendEmptyMessage(SHOW_FAILURE);
- }
- }) {
-
- @Override
- protected Map<String, String> getPostParams()
- throws AuthFailureError {
- Map<String, String> map = new HashMap<String, String>();
- map.put("romversion", serviceInfoMap.get("romversion"));
- map.put("brand", serviceInfoMap.get("brand"));
- map.put("model", serviceInfoMap.get("model"));
- map.put("device", serviceInfoMap.get("device"));
- map.put("imei", serviceInfoMap.get("imei"));
- Log.i(TEST_TAG, "发送结果为--->" + map.toString());
- return map;
- }
-
- };
- mQueue.add(jsonObjectRequest);
-
- }
这种方式应该可以,好像getParams也可以,因为服务器写的不是接受json格式数据,所以我没法测试。
还有就是去掉重写的方法,不管是getPostParams还是getParams,然后将里面的map集合内容写道,new JsonObjectRequest之前,然后在JsonObject jsonObject = newJsonObject(map),然后将jsonObject作为第三个参数,这样就传递了一个json字符串到服务器。
7.JsonObject和JsonArray
-
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("UserName", "ZHULI");
- jsonObject.put("age", "30");
- jsonObject.put("workIn", "ALI");
- System.out.println("jsonObject1:" + jsonObject);
-
-
- HashMap<String, String> hashMap = new HashMap<String, String>();
- hashMap.put("UserName", "ZHULI");
- hashMap.put("age", "30");
- hashMap.put("workIn", "ALI");
- System.out.println("jsonObject2:" + JSONObject.fromObject(hashMap));
-
-
- JSONArray jsonArray = new JSONArray();
- jsonArray.add(0, "ZHULI");
- jsonArray.add(1, "30");
- jsonArray.add(2, "ALI");
- System.out.println("jsonArray1:" + jsonArray);
-
-
- ArrayList<String> arrayList = new ArrayList<String>();
- arrayList.add("ZHULI");
- arrayList.add("30");
- arrayList.add("ALI");
- System.out.println("jsonArray2:" + JSONArray.fromObject(arrayList));
-
-
- System.out.println("jsonArray FROM HASHMAP:" + JSONArray.fromObject(hashMap));
-
-
- JSONObject jsonObject2 = new JSONObject();
- jsonObject2.put("UserName", "ZHULI");
- jsonObject2.put("age", "30");
- jsonObject2.put("workIn", "ALI");
- jsonObject2.element("Array", arrayList);
- System.out.println("jsonObject2:" + jsonObject2);
system结果:
- jsonObject1:{"UserName":"ZHULI","age":"30","workIn":"ALI"}
- jsonObject2:{"workIn":"ALI","age":"30","UserName":"ZHULI"}
- jsonArray1:["ZHULI","30","ALI"]
- jsonArray2:["ZHULI","30","ALI"]
- jsonArray FROM HASHMAP:[{"workIn":"ALI","age":"30","UserName":"ZHULI"}]
- jsonObject2:{"UserName":"ZHULI","age":"30","workIn":"ALI","Array":["ZHULI","30","ALI"]}
- </pre><pre name="code" class="html" style="font-size: 13px; margin-top: 0px; margin-bottom: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; line-height: 19.5px; background-color: rgb(254, 254, 242);">
- <span style="font-size:24px;">android读取json数据(遍历JSONObject和JSONArray)</span>
- <pre name="code" class="java">public String getJson(){
- String jsonString = "{\"FLAG\":\"flag\",\"MESSAGE\":\"SUCCESS\",\"name\":[{\"name\":\"jack\"},{\"name\":\"lucy\"}]}";//json字符串
- try {
- JSONObject result = new JSONObject(jsonstring);//转换为JSONObject
- int num = result.length();
- JSONArray nameList = result.getJSONArray("name");//获取JSONArray
- int length = nameList.length();
- String aa = "";
- for(int i = 0; i < length; i++){//遍历JSONArray
- Log.d("debugTest",Integer.toString(i));
- JSONObject oj = nameList.getJSONObject(i);
- aa = aa + oj.getString("name")+"|";
-
- }
- Iterator<?> it = result.keys();
- String aa2 = "";
- String bb2 = null;
- while(it.hasNext()){//遍历JSONObject
- bb2 = (String) it.next().toString();
- aa2 = aa2 + result.getString(bb2);
-
- }
- return aa;
- } catch (JSONException e) {
- throw new RuntimeException(e);
- }
- }
8.生成数组json串
我想要生成的json串为:
{
"languages": [//应用市场所支持的语种信息
{
"name":"汉语",
"code":"hy",
"selected":"true"
},
{
"name":"蒙古语",
"code":"mn"
"selected":"false"
}
],
"applist_versioncode":"0",
"applist_num":"2",
}
代码如下:
- private void createJsonData() {
- try {
-
- JSONObject jsonObject = new JSONObject();
-
-
-
- JSONArray jsonArrayLang = new JSONArray();
-
- JSONObject joLang0 = new JSONObject();
- joLang0.put("name", "汉语");
- joLang0.put("code", "hy");
- joLang0.put("selected", "true");
-
- jsonArrayLang.put(0, joLang0);
-
-
- JSONObject joLang1 = new JSONObject();
- joLang1.put("name", "蒙古语");
- joLang1.put("code", "mn");
- joLang1.put("selected", "false");
-
- jsonArrayLang.put(1, joLang1);
-
-
-
- jsonObject.put("languages", jsonArrayLang);
-
- jsonObject.put("applist_versioncode", "0");
-
- jsonObject.put("applist_num", "2");
-
- System.out.println(jsonObject.toString());
-
- } catch (JSONException e) {
-
- e.printStackTrace();
- }
- }
最后输出结果为
9.修改json串(带数组)
- String stt = "{\"languages\":[{\"name\":\"汉语\",\"code\":\"hy\"},"
- + "{\"name\":\"蒙古语\",\"code\":\"mn\"}]}";
- <span style="white-space:pre"> </span>try {
- JSONObject jsonObject = new JSONObject(stt);
- System.out.println("修改之前---->" + jsonObject.toString());
- JSONArray jsonArray = jsonObject.getJSONArray("languages");
- System.out.println("修改之前---->" + jsonArray.toString());
- System.out.println("jsonArray.length()---->"
- + jsonArray.length());
- for (int i = 0; i < jsonArray.length(); i++) {
- JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
- System.out.println("jsonObject2---->" + i + "-----"
- + jsonArray.toString());
- if (i == (jsonArray.length() - 1)) {
- System.out.println("修改之前---->");
- jsonObject2.put("name", "法国与");
- jsonArray.put(i, jsonObject2);
- }
- }
- jsonArray.put(jsonArray.length(),
- (JSONObject) jsonArray.opt(jsonArray.length() - 1));
- jsonObject.put("languages", jsonArray);
- System.out.println("修改之后---->" + jsonObject.toString());
- } catch (JSONException e) {
- e.printStackTrace();
- }
修改json串,就需要一层一层读出来,然后key值存在的时候,直接put新值,就会直接替换掉,然后在一层一层添加回去。这样就可以了
android与服务器交互总结(json,post,xUtils,Volley)
标签:
原文地址:http://www.cnblogs.com/wanghuaijun/p/5864520.html