开发需求是要android终端和server端互相传递json格式的数据。写了一个demo,android终端发送json格式的数据到server。发送代码片断如下:
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost("http://192.168.0.199:8080/ipformat/my.jsp"); HttpParams httpParams = new BasicHttpParams(); List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(); JSONObject jsonObject = new JSONObject(); Product product = new Product(); product.setLocation("深圳"); product.setName("腾讯"); jsonObject.put("product",product ); nameValuePair.add(new BasicNameValuePair("jsonString",jsonObject.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); httpPost.setParams(httpParams); Log.v("http"," send http"); httpClient.execute(httpPost); } catch (Exception e) { throw new RuntimeException(e); }
首先给Product赋值,然后转成json格式数据,作为http request的jsonString参数值传递到server端。