访问网络工具

package helper;

import android.os.AsyncTask;

import com.google.common.io.CharStreams;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Helper {
    public Helper() {

    }
    public Helper get(String url){
        MyAsyncTack get = new MyAsyncTack( url, "GET" );
        get.execute(  );
        return this;
    }
    public Helper post(){
        return this;
    }
    public class MyAsyncTack extends AsyncTask<String,Integer,String>{
        private String url;
        private String method;

        public MyAsyncTack(String url, String method) {
            this.url = url;
            this.method = method;
        }

        @Override
        protected String doInBackground(String... strings) {
            String data = "";
            try {
                URL murl = new URL( url);
                HttpURLConnection connection = (HttpURLConnection) murl.openConnection();
                connection.setRequestMethod( method );
                connection.setConnectTimeout( 5000 );
                connection.connect();
                int code = connection.getResponseCode();
                if (code == HttpURLConnection.HTTP_OK){
                    InputStream inputStream = connection.getInputStream();
                    data = CharStreams.toString( new InputStreamReader( inputStream, "UTF-8" ) );
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return data;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute( s );
            getMethod.Success( s );
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate( values );
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    }
    public getMethod getMethod;

    public interface getMethod{
        void Success(String data);
        void Error();
    }
    public void result(getMethod getMethod){
        this.getMethod = getMethod;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_42250299/article/details/82777477