你的位置:首页 > 操作系统

[操作系统]Http请求通信(工具类)

Http请求通信(工具类)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             @Override14             public void onError(Exception e) {15               // 异常情况进行处理16               Toast.makeText(mContext, e.getMessage(), 0).show();17             }18 19           });

 

 1   private Handler handler = new Handler() { 2  3     public void handleMessage(Message msg) { 4       String response = (String) msg.obj; 5       switch (msg.what) { 6       case ###: 7  8         break; 9 10       default:11         break;12       }13 14     }15   };

 

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       @Override15       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 }