Http请求通信(工具类)
异步消息处理流程是:
首先需要在主线程当中创建一个Handle对象,并重写handlerMessage()方法。
然后当子线程中需要进行UI操作时,就创建一个Message对象,并通过Handler将这条消息发送出去。
之后这条消息会被添加到MessageQueue的队列中等待被处理,而Loop则会一直尝试从MessageQueue中取出待处理消息,最后分发回HandlerMessage()方法中。
1 private Handler handler = new Handler() { 2 3 public void handleMessage(Message msg) { 4 String response = (String) msg.obj; 5 switch (msg.what) {//根据收到的消息的what类型处理 6 case ###: 7 8 break; 9 default: 10 super.handleMessage(msg);//这里最好对不需要或者不关心的消息抛给父类,避免丢失消息 11 break; 12 } 13 }
sendHttpRequest方法有两个参数 1.请求地址 2.请求Json字符串。
1 HttpUtil.sendHttpRequest(请求地址, 请求Json), 2 new HttpCallbackListener() { 3 4 @Override 5 public void onFinish(String response) { 6 // 返回内容执行具体的逻辑 7 Message message = new Message(); 8 message.what = ###; 9 message.obj = response; 10 handler.sendMessage(message); 11 } 12 13 @Override 14 public void onError(Exception e) { 15 // 异常情况进行处理 16 Toast.makeText(mContext, e.getMessage(), 0).show(); 17 } 18 19 });
Http请求通信(工具类):
1 public class HttpUtil { 2 3 public interface HttpCallbackListener { 4 5 void onFinish(String response); 6 7 void onError(Exception e); 8 } 9 10 public static void sendHttpRequest(final String urlStr, 11 final String jsonStr, final HttpCallbackListener listener) { 12 new Thread(new Runnable() { 13 14 @Override 15 public void run() { 16 HttpURLConnection connection = null; 17 try { 18 byte[] json = jsonStr.getBytes(); 19 URL url = new URL(urlStr); 20 connection = (HttpURLConnection) url.openConnection(); 21 connection.setDoOutput(true); 22 connection.setDoInput(true); 23 connection.setRequestMethod("POST"); 24 connection.setUseCaches(false); 25 connection.setConnectTimeout(5000); 26 connection.setInstanceFollowRedirects(true); 27 connection.setRequestProperty("Content-Type", 28 String.valueOf(json.length)); 29 connection.getOutputStream().write(json); // 通过输出流把数据写到服务器 30 // if (connection.getResponseCode() == 200) { 31 // 服务器返回的数据 32 BufferedReader in = new BufferedReader( 33 new InputStreamReader(connection.getInputStream())); 34 String line; 35 StringBuilder response = new StringBuilder(); 36 while ((line = in.readLine()) != null) { 37 response.append(line); 38 } 39 if (listener != null) { 40 listener.onFinish(response.toString()); 41 } 42 // } 43 } catch (Exception e) { 44 if (listener != null) { 45 listener.onError(e); 46 } 47 48 } finally { 49 if (connection != null) { 50 connection.disconnect(); 51 } 52 } 53 } 54 }).start(); 55 } 56 57 }