PostContent

来源:互联网 发布:丁丁定位软件介绍 编辑:程序博客网 时间:2024/05/03 19:30
public class PostContent extends Thread {private static final String TAG = "PostContent";private GetContentListener listener;private String urlString;private List<BasicNameValuePair> pairs;public PostContent(String string, List<BasicNameValuePair> pList) {urlString = Content.SERVICE_URL + string;pairs = pList;}private Handler handler = new Handler(Looper.myLooper()) {@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);switch (msg.what) {case 0:listener.onSucceed((String) msg.obj);break;case 1:listener.onFailed((String) msg.obj);break;default:break;}}};public synchronized void setGetContentListener(GetContentListener contentListener) {listener = contentListener;}public void setUrlString(String string, List<BasicNameValuePair> pList) {urlString = Content.SERVICE_URL + string;pairs = pList;}@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();new Runnable() {public synchronized void run() {HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost(urlString);UrlEncodedFormEntity entity;try {entity = new UrlEncodedFormEntity(pairs, "UTF-8");post.setEntity(entity);HttpResponse httpResponse = client.execute(post);HttpEntity httpEntity = httpResponse.getEntity();if (httpEntity != null) {String content = EntityUtils.toString(httpEntity, "UTF-8");JSONObject object = new JSONObject(content);checkContent(object);}else{transfrom("服务器连接失败!", 1);}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (JSONException e) {// TODO Auto-generated catch blocktransfrom("服务器连接失败!", 1);e.printStackTrace();} finally {client.getConnectionManager().shutdown();}}}.run();}public void checkContent(JSONObject object) {try {int code = object.getInt("status");if (code == 200) {String success = object.getString("data");transfrom(success, 0);} else {String faile = object.getString("message");transfrom(faile, 1);}} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public synchronized void transfrom(String string, int what) {Message message = new Message();message = new Message();message.obj = string;message.what = what;handler.sendMessage(message);}}


0 0
原创粉丝点击