欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

网络封装类

程序员文章站 2022-06-05 21:01:58
...

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();
}

}