android post数据到服务器端工具类(包括postjson字符串、键值对)

应用开发中出现这种需求,需要统计链接点击事件的记录,并在每次退出应用时向服务器上传本次使用应用过程中所有的事件记录。

首先将事件封装为一个实体类:

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());// 获取当前时间
        String str = formatter.format(curDate);
        this.time = str;
        // 同时给事件的imei字段赋值
        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;
    }
 

}


其中的时间和IMEI字段是由系统自动赋值的。

之后添加时间处理类:(这里主要是事件的增添,将事件列表转换为需要的json格式)

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;

/*这个是使用最笨的方法,拼接处一个json类型的字符串,其实可以使用jsonArray,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; }
     */
    /* 将list数据转换成需要提交的json数据 */
    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();

    }

}

之后就是json上传到doPost方法

自己之前的误区是post方法上传一定是通过key-value对的形式进行上传,其实post也可以单独上传一个json或者xml格式的数据,此时需要指定其contentType属性。

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");
  
//上面的类型设置是关键
post.setEntity(entity); httpResponse
= new DefaultHttpClient().execute(post); return httpResponse.getStatusLine().getStatusCode() ; } catch (Exception e) { e.printStackTrace(); return 0; } }

 关于http协议的详细内容参见这篇博客:

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

如果是通过简直对的方法post数据到服务器,并且服务器端返回字符串结果,方法如下

public static String postData(String path,List<NameValuePair> list){
        try {
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params, 6000);
            HttpConnectionParams.setSoTimeout(params, 6000);
            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的学习笔记  阅读(870)  评论(0编辑  收藏  举报