网络封装类
package com.example.yuemo.ui.util;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Handler;
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;
import java.net.URLConnection;
public class Util {
public interface NewBack{
void onsuccess(T o);
}
@SuppressLint(“StaticFieldLeak”)
public void getQuest3(final String apiUrl, final Class clazz, final NewBack newBack){
new AsyncTask<String, Void, Object>() {
@Override
protected Object doInBackground(String… strings) {
Object quest1 = getQuest1(strings[0], clazz);
return quest1;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
newBack.onsuccess(o);
}
}.execute(apiUrl);
}
public <T> T getQuest1(String apiUrl,Class clazz){
String quest = getQuest(apiUrl);
T o = (T) new Gson().fromJson(quest, clazz);
return o;
}
public String getQuest(String apiUrl){
String request="";
try {
URL url = new URL(apiUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
int responseCode = urlConnection.getResponseCode();
if (responseCode==200){
InputStream inputStream = urlConnection.getInputStream();
request = stream2String(inputStream);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return request;
}
public String stream2String(InputStream inputStream) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
for (String tmp=bufferedReader.readLine();tmp!=null;tmp=bufferedReader.readLine()){
stringBuilder.append(tmp);
}
return stringBuilder.toString();
}
}
上一篇: 网络判断和设置网络(有网无网)
下一篇: 封装网络请求