**HTTPURLConnection网络请求**

MainActivity.java
package com.example.week02;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

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;
import java.util.List;

public class MainActivity extends AppCompatActivity {

private ListView lv;
private String url="http://api.expoon.com/AppNews/getNewsList/type/1/p/1";
private MAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv = findViewById(R.id.lv);
    mAdapter = new MAdapter(MainActivity.this);
    lv.setAdapter(mAdapter);
    //创建一个方法
    initload();
}

private void initload() {
    new AsyncTask<String, Void, List<Gson.DataBean>>() {
        @Override
        protected List<Gson.DataBean> doInBackground(String... strings) {
            Gson gson=null;
            try {
                //获取地址
                URL url = new URL(strings[0]);
                //设置请求方法
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("GET");
                //设置连接超时
                httpURLConnection.setConnectTimeout(5000);
                //设置读取超时
                httpURLConnection.setReadTimeout(5000);
                //结果码
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode==200){
                    String result=stram2String(httpURLConnection.getInputStream());
                    gson = new com.google.gson.Gson().fromJson(result, Gson.class);
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return gson==null?null:gson.getData();
        }

        @Override
        protected void onPostExecute(List<Gson.DataBean> dataBeans) {
            super.onPostExecute(dataBeans);
            if (dataBeans==null){
                Toast.makeText(MainActivity.this,"请求失败",Toast.LENGTH_LONG).show();
                return;
            }
            mAdapter.setData(dataBeans);
        }
    }.execute(url);
}

private String stram2String(InputStream inputStream) {
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader isr = new BufferedReader(new InputStreamReader(inputStream));
    try {
        for (String temp=isr.readLine();temp!=null;temp=isr.readLine()){
            stringBuilder.append(temp);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stringBuilder.toString();
}

}
解析Gson串
package com.example.week02;

import java.util.List;

public class Gson {

private int status;
private String info;
private List<DataBean> data;

public int getStatus() {
    return status;
}

public void setStatus(int status) {
    this.status = status;
}

public String getInfo() {
    return info;
}

public void setInfo(String info) {
    this.info = info;
}

public List<DataBean> getData() {
    return data;
}

public void setData(List<DataBean> data) {
    this.data = data;
}

public static class DataBean {


    private String news_id;
    private String news_title;
    private String news_summary;
    private String pic_url;

    public String getNews_id() {
        return news_id;
    }

    public void setNews_id(String news_id) {
        this.news_id = news_id;
    }

    public String getNews_title() {
        return news_title;
    }

    public void setNews_title(String news_title) {
        this.news_title = news_title;
    }

    public String getNews_summary() {
        return news_summary;
    }

    public void setNews_summary(String news_summary) {
        this.news_summary = news_summary;
    }

    public String getPic_url() {
        return pic_url;
    }

    public void setPic_url(String pic_url) {
        this.pic_url = pic_url;
    }
}

}
Adapter优化
package com.example.week02;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;

public class MAdapter extends BaseAdapter {
private Context context;
private List<Gson.DataBean> list;

public MAdapter(MainActivity mainActivity) {
    context = mainActivity;
    list=new ArrayList<>();
}

public void setData(List<Gson.DataBean> dataBeans) {
    list.clear();
    if (dataBeans!=null){
        list.addAll(dataBeans);
    }
    notifyDataSetChanged();
}

@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int position) {
    return list.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Holder holder;
    if (convertView==null){
        holder=new Holder();
        convertView=LayoutInflater.from(context).inflate(R.layout.item,parent,false);
        holder.t1 =(TextView) convertView.findViewById(R.id.t1);
        holder.t2 =(TextView) convertView.findViewById(R.id.t2);
        holder.t3 =(TextView) convertView.findViewById(R.id.t3);
        holder.image1 =(ImageView) convertView.findViewById(R.id.image1);
        convertView.setTag(holder);
    }else{
        holder = (Holder) convertView.getTag();
    }
    ImageLoader.getInstance().displayImage(list.get(position).getPic_url(),holder.image1,Config.displayImageOptions());
    holder.t1.setText(list.get(position).getNews_id());
    holder.t2.setText(list.get(position).getNews_summary());
    holder.t3.setText(list.get(position).getNews_title());
    return convertView;
}
class Holder{

    ImageView image1;
    TextView t3;
    TextView t2;
    TextView t1;
}

}
** Config类**
package com.example.week02;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;

public class Config {
public static DisplayImageOptions displayImageOptions(){
DisplayImageOptions displayImageOptions=new DisplayImageOptions.Builder()
.cacheInMemory(true)//是否缓存到内存
.displayer(new CircleBitmapDisplayer())
.cacheOnDisk(true)//是否缓存到磁盘
.build();
return displayImageOptions;
}
}
App类
package com.example.week02;

import android.app.Application;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class Myapp extends Application {
@Override
public void onCreate() {
super.onCreate();
ImageLoaderConfiguration imageLoaderConfiguration=new ImageLoaderConfiguration.Builder(this)
.diskCacheSize(1010241024)
.memoryCacheSize(10)
.defaultDisplayImageOptions(Config.displayImageOptions())
.build();
ImageLoader.getInstance().init(imageLoaderConfiguration);
}
}
mainActivity.xml布局

<?xml version="1.0" encoding="utf-8"?>

<ListView
    android:id="@+id/lv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></ListView>

item布局

<?xml version="1.0" encoding="utf-8"?>


<TextView
    android:id="@+id/t1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="nihao"
    android:layout_toRightOf="@+id/image1"
    />
<TextView
    android:id="@+id/t2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="nihao"
    android:layout_below="@+id/t1"
    android:layout_toRightOf="@+id/image1"
    />
<TextView
    android:id="@+id/t3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="nihao"
    android:layout_below="@+id/t2"
    android:layout_toRightOf="@+id/image1"
    />
<TextView
    android:id="@+id/t4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="nihao"
    android:layout_below="@+id/t3"
    android:layout_toRightOf="@+id/image1"
/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值