使用XRecyclerView和Fresco实现切换视图列表展示数据和加载图片
使用的权限和依赖
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.INTERNET"/>
implementation rootProject.ext.dependencies["appcompat-v7"] implementation rootProject.ext.dependencies["constraint-layout"] implementation rootProject.ext.dependencies["retrofit2"] implementation rootProject.ext.dependencies["converter-gson"] implementation rootProject.ext.dependencies["rxjava2"] implementation rootProject.ext.dependencies["rxjava2:rxandroid"] implementation rootProject.ext.dependencies["dagger"] annotationProcessor rootProject.ext.dependencies["dagger-compiler"] implementation rootProject.ext.dependencies["adapter-rxjava"] implementation 'com.facebook.fresco:fresco:0.12.0' // 支持 GIF 动图,需要添加 implementation 'com.facebook.fresco:animated-gif:0.12.0' implementation 'com.android.support:support-v4:27.1.1' implementation 'com.sunfusheng:marqueeview:1.3.3' implementation 'com.jcodecraeer:xrecyclerview:1.3.2' implementation 'com.youth.banner:banner:1.4.10' implementation 'com.android.support:design:27.1.1' implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.4-7' implementation 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
build.gradle
apply from: "config.gradle"
config.gradle
ext { android = [ compileSdkVersion: 27, applicationId : "com.bwie.test.mylistpicture", minSdkVersion : 15, targetSdkVersion : 27, versionCode : 1, versionName : "1.0" ] dependencies = [ "appcompat-v7" : "com.android.support:appcompat-v7:27.1.1", "constraint-layout": "com.android.support.constraint:constraint-layout:1.1.0", "retrofit2" : "com.squareup.retrofit2:retrofit:2.4.0", "converter-gson" : "com.squareup.retrofit2:converter-gson:2.4.0", "adapter-rxjava" : "com.squareup.retrofit2:adapter-rxjava2:2.4.0", "rxjava2" : "io.reactivex.rxjava2:rxjava:2.1.13", "rxjava2:rxandroid": "io.reactivex.rxjava2:rxandroid:2.0.2", "dagger" : "com.google.dagger:dagger:2.8", "dagger-compiler" : "com.google.dagger:dagger-compiler:2.7" ] }
activity_main
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <RadioGroup android:id="@+id/rg" android:layout_alignParentBottom="true" android:layout_width="match_parent" android:orientation="horizontal" android:layout_height="60dp"> <RadioButton android:id="@+id/rbList" android:layout_weight="1" android:layout_width="0dp" android:text="列表" android:gravity="center" android:button="@null" android:layout_height="match_parent"/> <RadioButton android:id="@+id/rbPicture" android:layout_weight="1" android:layout_width="0dp" android:text="图片" android:gravity="center" android:button="@null" android:layout_height="match_parent"/> <Button android:id="@+id/btnEliminate" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="#f1f1f1" android:text="清除缓存"/> </RadioGroup> <FrameLayout android:id="@+id/flContent" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/rg" /> </RelativeLayout>
fragment_list
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="50dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:textSize="18dp" android:text="列表"/> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:layout_marginTop="1dp" android:background="#000000"/> <com.jcodecraeer.xrecyclerview.XRecyclerView android:id="@+id/xrecy_view" android:layout_marginTop="4dp" android:layout_width="match_parent" android:layout_height="match_parent"> </com.jcodecraeer.xrecyclerview.XRecyclerView> </LinearLayout>
fragment_mypicture
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="50dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="12dp" android:textSize="18dp" android:text="图片"/> </RelativeLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:layout_marginTop="1dp" android:background="#000000"/> <Button android:id="@+id/btn_Load" android:layout_width="match_parent" android:layout_height="48dp" android:layout_marginTop="18dp" android:background="#fdfdfd" android:layout_gravity="center_horizontal|center_vertical" android:text="加载图片"/> <ImageView android:id="@+id/iv_img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher" android:layout_marginTop="20dp" android:layout_gravity="center_horizontal"/> </LinearLayout>
item_mylist
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <com.facebook.drawee.view.SimpleDraweeView android:layout_width="100dp" android:id="@+id/img" android:layout_height="100dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="100dp" android:orientation="vertical"> <TextView android:id="@+id/tv1" android:layout_width="match_parent" android:layout_height="50dp" android:textSize="20sp" /> <TextView android:id="@+id/tv2" android:layout_width="match_parent" android:layout_height="50dp" android:textColor="#CCCC99" /> </LinearLayout> </LinearLayout>
MainActivity
import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; import android.widget.FrameLayout; import android.widget.RadioButton; import android.widget.RadioGroup; public class MainActivity extends AppCompatActivity { //创建5个Fragment private FrameLayout mFlContent; private MyListFragment myListFragment; private MyPictureFragment myPictureFragment; private RadioGroup mRg; private FragmentManager fragmentManager; private RadioButton mRbList;//列表 private RadioButton mRbPicture;//图片 private Button mBtnEliminate;//清除缓存 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //隐藏原有标题 getSupportActionBar().hide(); initView(); fragmentManager = getSupportFragmentManager(); myListFragment = new MyListFragment(); myPictureFragment = new MyPictureFragment(); fragmentManager.beginTransaction().replace(R.id.flContent, myListFragment).commit(); setListenter(); } private void setListenter() { mRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId){ case R.id.rbList: fragmentManager.beginTransaction().replace(R.id.flContent, myListFragment) .commit(); break; case R.id.rbPicture: fragmentManager.beginTransaction().replace(R.id.flContent, myPictureFragment) .commit(); break; } } }); } private void initView() { mFlContent = (FrameLayout) findViewById(R.id.flContent); mRbList = (RadioButton) findViewById(R.id.rbList); mRbPicture = (RadioButton) findViewById(R.id.rbPicture); mBtnEliminate = (Button) findViewById(R.id.btnEliminate); mRg = (RadioGroup) findViewById(R.id.rg); } }
MyListFragment
import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bwie.test.adapter.MyAdapter; import com.bwie.test.bean.MyListBean; import com.bwie.test.component.DaggerHttpComponent; import com.bwie.test.module.HttpModule; import com.bwie.test.mylistpicture.base.BaseFragment; import com.bwie.test.mylistpicture.contract.MobileContract; import com.bwie.test.mylistpicture.presenter.MobilePresenter; import com.jcodecraeer.xrecyclerview.XRecyclerView; import java.util.ArrayList; import java.util.List; public class MyListFragment extends BaseFragment<MobilePresenter> implements MobileContract.View{ private View view; private XRecyclerView mXrlv; private boolean isRefresh = true; private MyAdapter adapter; @Override public int getContentLayout() { return R.layout.fragment_mylist; } @Override public void inject() { DaggerHttpComponent.builder() .httpModule(new HttpModule()) .build() .inject(this); } @Override public void initView(View view) { mXrlv = (XRecyclerView) view.findViewById(R.id.xrecy_view); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()); mXrlv.setLayoutManager(linearLayoutManager); mPresenter.getMobile(); mXrlv.setLoadingListener(new XRecyclerView.LoadingListener() { @Override public void onRefresh() { isRefresh = true; mPresenter.getMobile(); } @Override public void onLoadMore() { isRefresh = false; mPresenter.getMobile(); } }); } @Override public void onSuccess(MyListBean mobileBean) { List<MyListBean.NewslistBean> tlist = new ArrayList<>(); tlist.addAll(mobileBean.getNewslist()); if (isRefresh){ adapter = new MyAdapter(getContext(), mobileBean.getNewslist()); mXrlv.setAdapter(adapter); adapter.refresh(tlist); mXrlv.refreshComplete(); } else { if (adapter != null){ adapter.loadMore(tlist); mXrlv.loadMoreComplete(); } } if (adapter == null){ return; } } }
MyPictureFragment
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.util.LruCache; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.bwie.test.utils.ExternalStorageUtils; import com.bwie.test.utils.HttpUtils; import java.lang.ref.SoftReference; import java.util.LinkedHashMap; public class MyPictureFragment extends Fragment implements View.OnClickListener{ private Button btn_download; private ImageView iv_img; private MyLruCache myLruCache; private LinkedHashMap<String, SoftReference<Bitmap>> cashMap = new LinkedHashMap<>(); private static final String TAG = "MainActivity"; private String imgPath = "http://img.taopic.com/uploads/allimg/140729/240450-140HZP45790.jpg"; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Bitmap bitmap = (Bitmap) msg.obj; iv_img.setImageBitmap(bitmap); Toast.makeText(getContext(), "从网络上下载图片", Toast.LENGTH_SHORT).show(); } }; private View view; /** * 加载图片 */ private Button mBtnDownload; private ImageView mIvImg; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_mypicture, container, false); initView(view); int totalMemory = (int) Runtime.getRuntime().maxMemory(); int size = totalMemory / 8; myLruCache = new MyLruCache(size); btn_download.setOnClickListener(this); return view; } private void initView(View view) { btn_download = (Button) view.findViewById(R.id.btn_Load); iv_img = (ImageView) view.findViewById(R.id.iv_img); } @Override public void onClick(View v) { Bitmap b = getImgCache(); if (b != null) { iv_img.setImageBitmap(b); } else { new Thread(new Runnable() { @Override public void run() { if (HttpUtils.isNetConn(getContext())) { byte b[] = HttpUtils.getDateFromNet(imgPath); if (b != null && b.length != 0) { Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length); Message msg = Message.obtain(); msg.obj = bitmap; handler.sendMessage(msg); myLruCache.put(imgPath, bitmap); Log.d(TAG, "run: " + "缓存到强引用中成功"); boolean bl = ExternalStorageUtils.storeToSDRoot("haha.jpg", b); if (bl) { Log.d(TAG, "run: " + "缓存到本地内存成功"); } else { Log.d(TAG, "run: " + "缓存到本地内存失败"); } } else { Toast.makeText(getContext(), "下载失败!", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getContext(), "请检查你的网络!", Toast.LENGTH_SHORT).show(); } } }).start(); } } /** * 从缓存中获取图片 */ public Bitmap getImgCache() { Bitmap bitmap = myLruCache.get(imgPath); if (bitmap != null) { Log.d(TAG, "getImgCache: " + "从LruCache获取图片"); } else { SoftReference<Bitmap> sr = cashMap.get(imgPath); if (sr != null) { bitmap = sr.get(); myLruCache.put(imgPath, bitmap); cashMap.remove(imgPath); Log.d(TAG, "getImgCache: " + "从软引用获取图片"); } else { bitmap = ExternalStorageUtils.getImgFromSDRoot("haha.jpg"); Log.d(TAG, "getImgCache: " + "从外部存储获取图片"); } } return bitmap; } public class MyLruCache extends LruCache<String, Bitmap> { public MyLruCache(int maxSize) { super(maxSize); } //返回每个图片的大小 @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight(); } @Override protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) { if (evicted) { SoftReference<Bitmap> softReference = new SoftReference<Bitmap>(oldValue); cashMap.put(key, softReference); } } } }
app文件夹下MyApp
import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; public class MyApp extends Application{ @Override public void onCreate() { super.onCreate(); //初始化fresco Fresco.initialize(this); } }
base文件夹下BaseContract
public interface BaseContract { interface BasePresenter<T extends BaseView>{ void attchView(T view); void detachView(); } interface BaseView{ void showLoading(); void dismissLoading(); } }
BaseFragment
import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.bwie.test.inter.IBase; import javax.inject.Inject; public abstract class BaseFragment <T extends BaseContract.BasePresenter> extends Fragment implements IBase,BaseContract.BaseView { @Inject protected T mPresenter; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); inject(); if (mPresenter!=null){ mPresenter.attchView(this); } } @Override public void onDestroy() { super.onDestroy(); if (mPresenter != null) { mPresenter.detachView(); } } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(getContentLayout(), null); initView(view); return view; } @Override public void showLoading() { } @Override public void dismissLoading() { } }
BasePresenter
public class BasePresenter <T extends BaseContract.BaseView> implements BaseContract.BasePresenter<T> { protected T mView; @Override public void attchView(T view) { this.mView=view; } @Override public void detachView() { if (mView!=null){ mView=null; } } }
contract文件夹下MobileContract
import com.bwie.test.bean.MyListBean; import com.bwie.test.mylistpicture.base.BaseContract; public interface MobileContract { interface View extends BaseContract.BaseView{ void onSuccess(MyListBean mobileBean); } interface Presenter extends BaseContract.BasePresenter<View> { void getMobile(); } }
presenter文件夹下MobilePresenter
import com.bwie.test.bean.MyListBean; import com.bwie.test.mylistpicture.base.BasePresenter; import com.bwie.test.mylistpicture.contract.MobileContract; import com.bwie.test.net.MobileAPi; import javax.inject.Inject; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class MobilePresenter extends BasePresenter<MobileContract.View> implements MobileContract.Presenter { private MobileAPi mobileAPi; @Inject public MobilePresenter(MobileAPi mobileAPi) { this.mobileAPi = mobileAPi; } @Override public void getMobile() { mobileAPi.getMobile() .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe( new Observer<MyListBean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(MyListBean listsBean) { if (mView!=null){ mView.onSuccess( listsBean ); } } @Override public void onError(Throwable e) { } @Override public void onComplete() { } } ); } }
adapter文件夹下MyAdapter
import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bwie.test.bean.MyListBean; import com.bwie.test.mylistpicture.R; import com.facebook.drawee.view.SimpleDraweeView; import java.util.List; public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; private List<MyListBean.NewslistBean> list; private LayoutInflater inflater; public MyAdapter(Context context, List<MyListBean.NewslistBean> list) { this.context = context; this.list = list; inflater=LayoutInflater.from(context); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = inflater.inflate( R.layout.item_mylist, parent, false); MobileViewHolder mobileViewHolder = new MobileViewHolder(view); return mobileViewHolder; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { MobileViewHolder mobileViewHolder= (MobileViewHolder) holder; MyListBean.NewslistBean newslistBean = list.get(position); mobileViewHolder.img.setImageURI(newslistBean.getPicUrl()); mobileViewHolder.tv1.setText(newslistBean.getTitle()); mobileViewHolder.tv2.setText(newslistBean.getCtime()); } @Override public int getItemCount() { return list.size(); } private class MobileViewHolder extends RecyclerView.ViewHolder { private final SimpleDraweeView img; private final TextView tv1; private final TextView tv2; public MobileViewHolder(View view) { super(view); img = view.findViewById(R.id.img); tv1 = view.findViewById(R.id.tv1); tv2 = view.findViewById(R.id.tv2); } } //刷新 public void refresh(List<MyListBean.NewslistBean> tlist){ this.list.clear(); this.list.addAll(tlist); notifyDataSetChanged(); } //加载更多 public void loadMore(List<MyListBean.NewslistBean> list){ this.list.addAll(list); notifyDataSetChanged(); } }
inter文件夹下IBase
import android.view.View; public interface IBase { int getContentLayout(); void inject(); void initView(View view); }
component文件夹下HttpComponent
import com.bwie.test.module.HttpModule; import com.bwie.test.mylistpicture.MyListFragment; import dagger.Component; @Component(modules = HttpModule.class) public interface HttpComponent { void inject(MyListFragment myListFragment); }
module文件夹下HttpModule
import com.bwie.test.net.Api; import com.bwie.test.net.MobileAPi; import com.bwie.test.net.MobileAPiService; import java.util.concurrent.TimeUnit; import dagger.Module; import dagger.Provides; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; @Module public class HttpModule { @Provides OkHttpClient.Builder providesOkHttpClientBuilder(){ return new OkHttpClient.Builder() .readTimeout(20, TimeUnit.MINUTES) .writeTimeout(20,TimeUnit.MINUTES) .connectTimeout(10,TimeUnit.MINUTES); } @Provides MobileAPi provideMobileAPi(OkHttpClient.Builder builder){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(Api.BASEURL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(builder.build()) .build(); MobileAPiService mobileAPiService = retrofit.create(MobileAPiService.class); return MobileAPi.getMobileAPi(mobileAPiService); } }
net文件夹下Api
public interface Api { String BASEURL = "http://api.tianapi.com/"; }
MobileAPi
import com.bwie.test.bean.MyListBean; import io.reactivex.Observable; public class MobileAPi { private static MobileAPi mobileAPi; private MobileAPiService mobileAPiService; public MobileAPi(MobileAPiService mobileAPiService) { this.mobileAPiService = mobileAPiService; } public static MobileAPi getMobileAPi(MobileAPiService mobileAPiService){ if (mobileAPi==null){ mobileAPi=new MobileAPi(mobileAPiService); } return mobileAPi; } public Observable<MyListBean> getMobile(){ return mobileAPiService.getMobile(); } }
MobileAPiService
import com.bwie.test.bean.MyListBean; import io.reactivex.Observable; import retrofit2.http.GET; public interface MobileAPiService { @GET("mobile/?key=71e58b5b2f930eaf1f937407acde08fe&num=10") Observable<MyListBean> getMobile(); }
utils文件夹下ExternalStorageUtils
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class ExternalStorageUtils { /** * 将传递过来的图片byte数组存储到sd卡中 */ public static boolean storeToSDRoot(String imgName, byte buff[]) { boolean b = false; String basePath = Environment.getExternalStorageDirectory().getAbsolutePath(); File file = new File(basePath, imgName); try { FileOutputStream fos = new FileOutputStream(file); fos.write(buff); fos.close(); b = true; } catch (IOException e) { e.printStackTrace(); } return b; } /** * 从本地内存中根据图片名字获取图片 */ public static Bitmap getImgFromSDRoot(String imgName) { Bitmap bitmap = null; String basePath = Environment.getExternalStorageDirectory().getAbsolutePath(); File file = new File(basePath, imgName); try { FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte b[] = new byte[1024]; int len; while ((len = fis.read(b)) != -1) { baos.write(b, 0, len); } byte buff[] = baos.toByteArray(); if (buff != null && buff.length != 0) { bitmap = BitmapFactory.decodeByteArray(buff, 0, buff.length); } } catch (IOException e) { e.printStackTrace(); } return bitmap; } }
HttpUtils
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpUtils { /** * 判断网络连接是否通畅 */ public static boolean isNetConn(Context mContext) { ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService( Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null) { return info.isConnected(); } else { return false; } } /** * 根据path下载网络上的数据 */ public static byte[] getDateFromNet(String path) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setDoInput(true); conn.connect(); if (conn.getResponseCode()==200) { InputStream is = conn.getInputStream(); byte b[] = new byte[1024]; int len; while ((len=is.read(b))!=-1) { baos.write(b, 0, len); } return baos.toByteArray(); } } catch (IOException e) { e.printStackTrace(); } return baos.toByteArray(); } }
bean文件夹下MyListBean
import java.util.List; public class MyListBean { private int code; private String msg; private List<NewslistBean> newslist; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List<NewslistBean> getNewslist() { return newslist; } public void setNewslist(List<NewslistBean> newslist) { this.newslist = newslist; } public static class NewslistBean { private String ctime; private String title; private String description; private String picUrl; private String url; public String getCtime() { return ctime; } public void setCtime(String ctime) { this.ctime = ctime; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } }