zoukankan      html  css  js  c++  java
  • 使用handler和Message获取xutils发送POST请求从服务器端返回数据

    注意:应该在handleMessage中处理从服务器返回的数据,否则会因为线程问题拿不到结果。另外可以在onSuccess方法中更新UI,因为xutils封装了handler。

    public class MainActivity extends Activity{
        private String responseInfo;
        private Handler handler;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    responseInfo = (String) msg.obj;
                    Gson gson = new Gson();
                    Type type = new TypeToken<JsonBean>() {
                    }.getType();
                    JsonBean jsonBean = gson.fromJson(responseInfo, type);
                    System.out.println(jsonBean);
                }
            };
            getFromServer();
        }
        
        /**
         * 使用xutils发送POST请求得到服务器返回的数据
         */
        public void getFromServer() {
            String url = "http://182.92.195.162:8088/index.php?r=api/client/init";
            RequestParams params = new RequestParams();
            JSONObject json = new JSONObject();
            JSONObject request = new JSONObject();
            try {
                json.put("uid", "");
                json.put("sid", "");
                json.put("ver", "1");
                json.put("request", request);
                params.addBodyParameter("json", json.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            HttpUtils http = new HttpUtils();
            http.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {
                @Override
                public void onFailure(HttpException arg0, String arg1) {
    
                }
    
                @Override
                public void onSuccess(ResponseInfo<String> arg0) {
                    Message msg = Message.obtain();
                    msg.obj = arg0.result;
                    handler.sendMessage(msg);
                }
            });
        }
    }
  • 相关阅读:
    浏览器刷新缓存机制
    Asp.Net获取IP的方法
    c# 了解委托
    用什么方法来判断字符串是否存在的函数
    怎么样从地址中获得数据?
    新网站如何不被百度查封,请注意以下事项。
    搜索引擎如何抓取网页和如何索引网页?
    什么情况下include_path不起作用?
    用户注册演示程序操作案例
    用户提交的cookie提交时为什么传不到服务器
  • 原文地址:https://www.cnblogs.com/bianmajiang/p/3998101.html
Copyright © 2011-2022 走看看