Android中通过json向MySql中读写数据的方法Android中通过json向MySql中读写数据的方法.docx
文本预览下载声明
Android中通过json向MySql中读写数据的方法先说一下如何通过json将android程序中的数据上传到MySql中:首先定义一个类JSONParser.java类,将json上传数据的方法封装好,可以直接在主程序中调用该类,代码如下[java]?view plaincopypublic?class?JSONParser?{???static?InputStream?is?=?null;???static?JSONObject?jObj?=?null;???static?String?json?=?;???//?constructor???public?JSONParser()?{???}???//?function?get?json?from?url???//?by?making?HTTP?POST???public?JSONObject?makeHttpRequest(String?url,?String?method,???ListNameValuePair?params)?{???//?Making?HTTP?request???try?{???//?request?method?is?POST???//?defaultHttpClient???DefaultHttpClient?httpClient?=?new?DefaultHttpClient();???HttpPost?httpPost?=?new?HttpPost(url);???httpPost.setEntity(new?UrlEncodedFormEntity(params,HTTP.UTF_8));???HttpResponse?httpResponse?=?httpClient.execute(httpPost);???HttpEntity?httpEntity?=?httpResponse.getEntity();???is?=?httpEntity.getContent();???}?catch?(UnsupportedEncodingException?e)?{???e.printStackTrace();???}?catch?(ClientProtocolException?e)?{???e.printStackTrace();???}?catch?(IOException?e)?{???e.printStackTrace();???}???try?{???BufferedReader?reader?=?new?BufferedReader(new?InputStreamReader(???is,?UTF-8));???StringBuilder?sb?=?new?StringBuilder();???String?line?=?null;???while?((line?=?reader.readLine())?!=?null)?{???sb.append(line?+?\n);???}???is.close();???json?=?sb.toString();???}?catch?(Exception?e)?{???Log.e(Buffer?Error,?Error?converting?result??+?e.toString());???Log.d(json,?json.toString());???}???//?try?parse?the?string?to?a?JSON?object???try?{???jObj?=?new?JSONObject(json);???}?catch?(JSONException?e)?{???Log.e(JSON?Parser,?Error?parsing?data??+?e.toString());???}???//?return?JSON?String???return?jObj;???}???}???[java]?view plaincopy??主程序中这样调用:? ? ? ? ?[java]?view plaincopy???????????????????????????????params?=?new?ArrayListNameValuePair();????????//这里可以替换成你自己程序中的一些键值对??params.add(new?BasicNameValuePair(time,?+time));???params.add(new?BasicNameValuePair(lat,?+lat));???params.add(new?BasicNameValuePair(lon,?+lon));??params.add(new?BasicNameValuePair(encyp
显示全部