例如:
发送方:
从类到Json字符串
String stringToClient = (new Gson()).toJson(messageObject)
接收方:
从Json字符串到类
YourClass object = (new Gson()).fromJson(stringFromServer, YourClass.class)
如果是图片或者媒体文件这样二进制的数据,需要先用base64转码,然后再发送。
Android客户端直接连接远程MySQL数据库的方法如下:String result = ""//首先使用NameValuePair封装将要查询的年数和关键字绑定ArrayList<NameValuePair>nameValuePairs = new ArrayList<NameValuePair>()nameValuePairs/getAllPeopleBornAfter.php")httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs))HttpResponse response = httpclient.execute(httppost)HttpEntity entity = response.getEntity()InputStream is = entity.getContent()}catch(Exception e){Log.e("log_tag", "Error in http connection "+e.toString())}//将HttpEntity转化为Stringtry{BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8)StringBuilder sb = new StringBuilder()String line = nullwhile ((line = reader.readLine()) != null) {sb.append(line + "\n")}is.close()result=sb.toString()}catch(Exception e){Log.e("log_tag", "Error converting result "+e.toString())}//将String通过JSONArray解析成最终结果try{JSONArray jArray = new JSONArray(result)for(int i=0i<jArray.length()i++){JSONObject json_data = jArray.getJSONObject(i)Log.i("log_tag","id: "+json_data.getInt("id")+", name: "+json_data.getString("name")+", sex: "+json_data.getInt("sex")+", birthyear: "+json_data.getInt("birthyear"))}}}catch(JSONException e){Log.e("log_tag", "Error parsing data "+e.toString())}虽然Android开发中可以直接连接数据库,但是实际中却不建议这么做,应该使用服务器端中转下完成。欢迎分享,转载请注明来源:内存溢出
评论列表(0条)