我自己做的。
JSonObject returnedJObject= new JSonObject();JSonObject KeyvalspairJObject=new JSonObject ();JSonObject devcKeyvalspairJObject=new JSonObject ();JSonObject capabilityJObject=new JSonObject();JSonObject ScreenDimensionsJObject =new JSonObject();JSonObject deviceJObject= new JSonObject();try{ KeyvalspairJObject.put("key1","val1"); KeyvalspairJObject.put("key2","val2"); capabilityJObject.put("sms", false); capabilityJObject.put("data", true); capabilityJObject.put("gps", true); capabilityJObject.put("wifi", true); capabilityJObject.put("keyValue", KeyvalspairJObject); ScreenDimensionsJObject.put("width", 45); ScreenDimensionsJObject.put("height", 45); devcKeyvalspairJObject.put("Devckey1","val1"); devcKeyvalspairJObject.put("DEVCkey2","val2"); deviceJObject.put("userAgent", "MYUserAgent"); deviceJObject.put("capabilities", capabilityJObject); deviceJObject.put("screen", ScreenDimensionsJObject); deviceJObject.put("keyValue", devcKeyvalspairJObject); returnedJObject.put("clientId", "ID:1234-1234"); returnedJObject.put("carrier","TMobile"); returnedJObject.put("device",deviceJObject); returnedJObject.put("time",1294617435); returnedJObject.put("msisdn","1234567890"); returnedJObject.put("timezone","GMT");}catch(JSonException e){}
这就是我们如何将JSON数据发送到服务器。
public String putDataToServer(String url,JSonObject returnedJObject) throws Throwable{ HttpPost request = new HttpPost(url); JSonStringer json = new JSonStringer(); StringBuilder sb=new StringBuilder(); if (returnedJObject!=null) { Iterator<String> itKeys = returnedJObject.keys(); if(itKeys.hasNext()) json.object(); while (itKeys.hasNext()) { String k=itKeys.next(); json.key(k).value(returnedJObject.get(k)); Log.e("keys "+k,"value "+returnedJObject.get(k).toString()); } } json.endObject(); StringEntity entity = new StringEntity(json.toString()); entity.setContentType("application/json;charset=UTF-8"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8")); request.setHeader("Accept", "application/json"); request.setEntity(entity); HttpResponse response =null; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpConnectionParams.setSoTimeout(httpClient.getParams(), Constants.ANDROID_CONNECTION_TIMEOUT*1000); HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),Constants.ANDROID_CONNECTION_TIMEOUT*1000); try{ response = httpClient.execute(request); } catch(SocketException se) { Log.e("SocketException", se+""); throw se; } InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while((line = reader.readLine()) != null){ sb.append(line); } return sb.toString();}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)