网络工具类 HttpUtils

package com.bwie.zjj.urils;

import android.os.AsyncTask;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtils {
    private static final HttpUtils ourInstance = new HttpUtils();
    private NetCallBack callBack;

    public void setCallBack(NetCallBack callBack) {
        this.callBack = callBack;
    }

    public interface NetCallBack{
        void onSuccess(String s);
        void onError(String errorMsg);

    }

    public static HttpUtils getInstance() {
        return ourInstance;
    }

    public HttpUtils() {

    }
    public void get(String url){
        new MyAsyncTask().execute(url);
    }

    class MyAsyncTask extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... strings) {
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setReadTimeout(5000);
                urlConnection.setConnectTimeout(5000);
                if(urlConnection.getResponseCode()==200){
                    return inputStream2String(urlConnection.getInputStream());
                }
            } catch (Exception e) {
                e.printStackTrace();

            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {

            if(s==null){
                callBack.onError("网络出错了");
            }else {
                callBack.onSuccess(s);
            }
        }
    }

    private String inputStream2String(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int len=-1;
        byte[] bytes = new byte[1024];
        while ((len=inputStream.read(bytes))!=-1){
            byteArrayOutputStream.write(bytes,0,len);
        }
        return new String(byteArrayOutputStream.toByteArray());

    }


}

猜你喜欢

转载自blog.csdn.net/weixin_42535797/article/details/80876901