package com.example.lianxi4;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Util {
//获取网络数据
private Gson gson;
private static Util instance;
//实例化gson
public Util(){
gson = new Gson();
}
//
public static Util getInstance(){
if(instance==null){
instance = new Util();
}
return instance;
}
public interface CallBack<T>{
void success(T t);
}
@SuppressLint("StaticFieldLeak")
public void getRequest(final String path, final Class clazz, final CallBack callBack){
new AsyncTask<String, Void, Object>() {
@Override
protected Object doInBackground(String... strings) {
return getRequest(path,clazz);
}
@Override
protected void onPostExecute(Object o) {
callBack.success(o);
}
}.execute(path);
}
public <T> T getRequest(String path,Class clazz){
return (T) gson.fromJson(getRequest(path), clazz);
}
public String getRequest(String path){
String result = "";
try {
URL url = new URL(path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == 200){
result = ToString(urlConnection.getInputStream());
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private String ToString(InputStream is) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
for(String mmp=br.readLine();mmp!=null;mmp = br.readLine()){
stringBuilder.append(mmp);
}
return stringBuilder.toString();
}
}