Handler消息机制和http网络请求

    xiaoxiao2022-06-22  21

    Handler消息机制 子线程不能修改UI界面,修改UI界面需要在主线程完成,这样引入了handler消息机制 Handler 消息处理器,用来把消息发送到Message Queue队列里,以及取出后发送给主线程 Message 发送消息 msg.what msg.obj Message Queue 消息队列,里面存放handler所设置进来的消息,按照时间去排序 Looper 轮询器 检查Message Queue里是否含有信息,如果有,通知handler发送给主线程 在主线程里,初始化Handler handler = new Handler 在子线程里初始化Message对象 设置msg的标识 利用handler发送消息 重写handler里的handlerMessage方法 ANR异常:Application not response 原因在主线程做了耗时的操作 网络请求(需要配置权限) HttpConnection GET方式使用 初始化URL对象(URL url = new URL(path)) 打开网络连接器 HttpUrlConnection conn = (HttpUrlConnection)url.openConnection(); conn.setConnectTimeout(毫秒值); conn.setRequestMethod(方法名); conn.getResponseCode(); conn.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(IO输入流); post请求和get请求的区别 get请求的参数拼接在url后面,没有请求体,使用简单 缺点:安全性不高,没有长度限制  post请求有请求头安全性高,没有长度限制 编写麻烦 HttpUrlConnection  URL url= new URL(); HttpUrlConnection ulr = (HttpUrlConnection)url.openConnection conn.setRequestMethod("POST"); conn.setRwquestProperty("Conten-Type","application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length",data.length); conn.setDoOutput(true); conn.getOutputStream.write(data.getBytes()); conn.getResponseCode(); HttpClient get请求 HttpClient client = new DefaultHttpClient() HttpGet get = new HttpGet(url) HttpResponse response = client.execute(get); int code = getStatuLine.getStatusCode(); InputStream is = response .getEntity.getContent(); EntityUtils.toString(response .getEntity.getContent()); HttpClient post请求 HttpClient client = new DefaultHttpClient() HttpPost post = new HttpPost(url); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("key",value)) post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8")); HttpResponse response=client.execute(post); int code = getStatusLine().getStatusCode(); 获取返回数据
    转载请注明原文地址: https://ju.6miu.com/read-1122728.html

    最新回复(0)