HttpUtil工具类

package com.baway.utils;

import android.os.AsyncTask;

import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {
    private static HttpUtil httpUtil = new HttpUtil();
    public static HttpUtil getInstance(){
        if(httpUtil == null){
            httpUtil = new HttpUtil();
        }
        return httpUtil;
    }
    //私有构造方法
    private HttpUtil() {

    }
    public void getUrl(String api,HttpCallback httpCallback){
        new HttpAsyncTask(httpCallback).execute(api);
    }

    class HttpAsyncTask extends AsyncTask,Void,String>{
        private HttpCallback httpCallback;
        private HttpURLConnection connection;

        public HttpAsyncTask(HttpCallback httpCallback) {
            this.httpCallback = httpCallback;
        }

        @Override
        protected String doInBackground(String... strings) {
            try{
                URL url = new URL(strings[0]);
                connection = (HttpURLConnection) url.openConnection();
                if(connection.getResponseCode()==200){
                    String str = SwapInputStreamToString.SwapInputStreamToString(connection.getInputStream());
                    return  str;
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            httpCallback.success(s);
        }
    }
    public interface HttpCallback{
        void success(String success);
    }
}

你可能感兴趣的:(资讯项目)