Android post data to server-side tool classes (including postjson strings and key value pairs)

This requirement arises in application development. It is necessary to count the records of link click events, and upload all the event records in the process of using the application to the server each time you exit the application.

First, encapsulate the event as an entity class:

 package com.wotlab.home.moneyplantairs.entity; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import android.content.Context; import android.net.sip.SipRegistrationListener; import android.telephony.TelephonyManager; public  class EventEntity implements Serializable { private String id; private String imei; private String time; public EventEntity(Context context) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" ); Date curDate = new Date(System.currentTimeMillis()); // Get the current time String str = formatter.format(curDate); this .time = str; // At the same time, assign a value to the imei field of the event TelephonyManager tm = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); this .imei= tm.getDeviceId(); } public String getTime() { return  this .time; } public String getId() { return id; } public  void setId(String id) { this .id = id; } public String getImei() { return imei; } }


The time and IMEI fields are automatically assigned by the system.

Then add a time processing class: (This is mainly about adding events, converting the event list to the required json format)

 package com.wotlab.home.moneyplantairs.utils; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.wotlab.home.moneyplantairs.entity.EventEntity; /* This is the most stupid method. A json type string at the splice can be converted using jsonArray and jsonObject */
 public  class StasticUtil { private ArrayList<EventEntity> eventlist = new ArrayList<EventEntity> (); private  static StasticUtil instance; private StasticUtil() { } public  static StasticUtil getInstance() { if (instance == null ) { instance = new StasticUtil(); } return instance; } public  void addEvent(EventEntity event) { this .eventlist.add(event); } /* * public ArrayList<EventEntity> getEventlist() { return eventlist; } */
     /* Convert the list data to the json data to be submitted */
     public String converToJson() { JSONArray array = new JSONArray(); for (EventEntity event : this .eventlist) { JSONObject obj = new JSONObject(); try { obj.put( "id" , event.getId()); obj.put( "time" , event.getTime()); obj.put( "imei" , event.getImei()); } catch (JSONException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } array.put(obj); } System.out.println(array.toString()); return array.toString(); } }

Then json uploads to the doPost method

My previous mistake was that the post method must upload data in the form of key value pairs. In fact, post can also upload data in json or xml format separately. At this time, you need to specify its contentType attribute.

 public  int doPost(String stringUrl, String json) { String result = null ; HttpPost post = new HttpPost(stringUrl);          HttpResponse httpResponse = null ; try { StringEntity entity = new StringEntity(json,HTTP.UTF_8); entity.setContentType( "application/json" );   
//The above type setting is the key
post.setEntity(entity); httpResponse
= new DefaultHttpClient().execute(post); return httpResponse.getStatusLine().getStatusCode() ; } catch (Exception e) { e.printStackTrace(); return zero ; } }

For details about http protocol, see this blog:

http://blog.sina.com.cn/s/blog_6040778d01014da3.html

If you post data to the server through an almost correct method, and the server returns string results, the method is as follows

 public  static String postData(String path,List<NameValuePair> list){ try { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, six thousand ); HttpConnectionParams.setSoTimeout(params, six thousand ); HttpPost httppost = new HttpPost(path); httppost.setParams(params); if (list != null ) { httppost.setEntity( new UrlEncodedFormEntity(list, HTTP.UTF_8)); } Log.d( "Req" , path); URI uri = httppost.getURI(); System.out.println(uri); HttpResponse httpResp = new DefaultHttpClient().execute(httppost); if (httpResp.getStatusLine().getStatusCode() == 200 ) { String result = EntityUtils.toString(httpResp.getEntity()); LogUtil.d( "Req" , result); return result; } } catch (Exception e) { e.printStackTrace(); } return "" ; }

 

posted @ 2013-05-24 11:11   Bobo's study notes   Reading( eight hundred and seventy Comments( zero edit   Collection   report