标签:
1 public class MainActivity extends Activity { 2 private String PATH = "https://www.baidu.com/"; 3 private TextView mTv; 4 @Override 5 protected void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.activity_main); 8 mTv = (TextView) findViewById(R.id.tv); 9 } 10 public void request(View view) { 11 NetWorkUtils.request(PATH, new RequestCallBack() { 12 @Override 13 public void onSuccess(String data) { 14 mTv.setText(data); 15 } 16 }); 17 } 18 }
1 public class NetWorkUtils { 2 3 public interface RequestCallBack { 4 public void onSuccess(String data); 5 } 6 7 public static void request(final String path, final RequestCallBack callBack) { 8 9 final Handler handler = new Handler() { 10 @Override 11 public void handleMessage(Message msg) { 12 String data = (String) msg.obj; 13 callBack.onSuccess(data); 14 } 15 }; 16 17 new Thread() { 18 @Override 19 public void run() { 20 try { 21 URL url = new URL(path); 22 23 HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 24 25 conn.setReadTimeout(25000); 26 conn.setConnectTimeout(25000); 27 conn.setRequestMethod("GET"); 28 29 int code = conn.getResponseCode(); 30 31 if (code == 200) { 32 InputStream is = conn.getInputStream(); 33 34 ByteArrayOutputStream bos = new ByteArrayOutputStream(); 35 int len = 0; 36 byte[] tmp = new byte[4096]; 37 38 while ((len = is.read(tmp)) != -1) { 39 bos.write(tmp, 0, len); 40 } 41 42 is.close(); 43 44 String str = bos.toString(); 45 46 Message.obtain(handler, 1, str).sendToTarget(); 47 } 48 } catch (MalformedURLException e) { 49 e.printStackTrace(); 50 } catch (IOException e) { 51 e.printStackTrace(); 52 } 53 54 } 55 }.start(); 56 } 57 }
标签:
原文地址:http://www.cnblogs.com/CodeUtils/p/4399086.html