package com.example.ggq.xiaomi.activity.net; import android.os.AsyncTask; import android.text.TextUtils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpUtils { private static final HttpUtils ourInstance = new HttpUtils(); private String TAG = HttpUtils.class.getSimpleName(); public static HttpUtils getInstance() { return ourInstance; } private HttpUtils() { } public void get(String url,NetCallback callback){ new loadData(callback).execute(url); } private class loadData extends AsyncTask<String,Void,String> { private NetCallback callback; public loadData(NetCallback callback) { this.callback = callback; } @Override protected String doInBackground(String... strings) { try { URL url = new URL(strings[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){ return inputStream2String(connection.getInputStream()); } } catch (Exception e) { e.printStackTrace(); callback.onError(e.getMessage()); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); if(!TextUtils.isEmpty(s)){ callback.onSuccess(s); }else { callback.onError("没有请求到数据!"); } } } private String inputStream2String(InputStream inputStream) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int len = -1; byte[] bytes = new byte[1024]; while ((len = inputStream.read(bytes)) != -1){ outputStream.write(bytes,0,len); } return new String(outputStream.toByteArray()); } public interface NetCallback { void onSuccess(String s); void onError(String errorMsg); } }
封装好的请求网络的接口
猜你喜欢
转载自blog.csdn.net/weixin_42470335/article/details/80848198
今日推荐
周排行