網路請求資料(Uitl工具類)
阿新 • • 發佈:2018-11-28
封裝工具類
package com.example.pullshuaixn;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
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 javax.security.auth.callback.Callback;
public class NetUtil { private static NetUtil netUtil; public NetUtil(){ } public static NetUtil getNetUtil(){ if (netUtil == null){ netUtil = new NetUtil(); } return netUtil; } public interface CallBak<T>{ void onsuccess(T t); } @SuppressLint("StaticFieldLeak") public void requsetData(String strurl, final Class clazz, final CallBak callback){ new AsyncTask<String, Void, Object>() { @Override protected Object doInBackground(String... strings) { return requsetData( strings[0],clazz ); } @Override protected void onPostExecute(Object o) { callback.onsuccess( o ); } }.execute( strurl ); } private <T>T requsetData(String string, Class clazz) { return (T) new Gson().fromJson( requsetData(string),clazz ); } private String requsetData(String str){ try { URL url = new URL(str); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); int responseCode = urlConnection.getResponseCode(); if(responseCode==200){ String s = streamTostring(urlConnection.getInputStream()); return s; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public String streamTostring(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder builder=new StringBuilder(); for (String tmp=bufferedReader.readLine();tmp!=null;tmp=bufferedReader.readLine()){ builder.append(tmp); } return builder.toString(); } }