其他

package com.example.month01_hy.ui.app;

import android.app.Application;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        initImageLoader();
    }

    private void initImageLoader() {
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(getApplicationContext()).build();
        ImageLoader.getInstance().init(configuration);
    }
}
package com.example.month01_hy.ui.net;

import android.os.AsyncTask;

import com.google.common.io.CharStreams;

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

/**
 * 网络请求工具类
 *
 * @author 轻舟已过万重山
 * @date 2018-8-22
 */
public class HttpUtils {
    private static final HttpUtils ourInstance = new HttpUtils();

    public static HttpUtils getInstance() {
        return ourInstance;
    }

    private HttpUtils() {
    }

    private GetDataCallBack getDataCallBack;
    public void setGetDataCallBack(GetDataCallBack getDataCallBack){
        this.getDataCallBack=getDataCallBack;
    }
    public void setUrl(String url){
        LoadDataTask loadDataTask = new LoadDataTask();
        loadDataTask.execute(url);
    }

    class LoadDataTask extends AsyncTask {

        @Override
        protected String doInBackground(String... strings) {
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                connection.setRequestMethod("GET");
                if (connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                    return CharStreams.toString(new InputStreamReader(connection.getInputStream(),"utf-8"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            getDataCallBack.CallBack(s);
            super.onPostExecute(s);
        }
    }
    //接口
    public interface GetDataCallBack{
        void CallBack(String result);
    }
}

 

你可能感兴趣的:(其他)