关于HttpUrlConnection和JSON结合使用的案例(跑跑APP为例)

一、第一部分:首先新建一个模块,创建出布局和主体类。在布局里定义出所需的控件,然后回到主体类里绑定ID
layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.myapplication12.MainActivity">

    <RelativeLayout
        android:id="@+id/relative1"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#FFD43232">

        <EditText
            android:layout_width="300dp"
            android:layout_height="match_parent" />

        <TextView
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="320dp"
            android:layout_marginTop="10dp"
            android:text="搜索"
            android:textColor="#ffff"
            android:textSize="20sp" />
    </RelativeLayout>

    <ImageView
        android:id="@+id/img"
        android:layout_width="match_parent"
        android:layout_height="350dp"
        android:layout_below="@id/relative1"
        android:scaleType="centerCrop"
        android:src="@mipmap/foodmhw" />

    <LinearLayout
        android:id="@+id/linerlayout"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_below="@id/img">

        <ImageView
            android:id="@+id/richang_btn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@mipmap/articles" />

        <ImageView
            android:id="@+id/food_btn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@mipmap/food" />

        <ImageView
            android:id="@+id/agency_btn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@mipmap/agency" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linerlayout2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000000"
        android:layout_below="@id/linerlayout">
        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="主页"
            android:textColor="#ffff"
            android:textSize="30sp"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="未完成"
            android:textColor="#ffff"
            android:textSize="30sp"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="已完成"
            android:textColor="#ffff"
            android:textSize="30sp"/>

    </LinearLayout>


</RelativeLayout>

效果图
这里写图片描述

MainActivity

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;



public class MainActivity extends AppCompatActivity implements OnClickListener {
    private ImageView richangBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bind();
    }

    private void bind() {
        richangBtn = findViewById(R.id.richang_btn);
        richangBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

二、第二部分:应要求,要点击效果图中的 日常用品 图像按钮则跳转到日常用品的列表中,如以下效果图所示
效果图:
这里写图片描述
1.首先新建一个layout_daily布局文件,在里面定义出ListView控件,为其绑定ID.
layout_daily:

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

    </ListView>

2.因为要详细的获取到列表里每一行具体的变量,所以我们还要创一个daily_item布局,用来详细的表示每一行的具体情况

<TextView
        android:id="@+id/daily_item_tv"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:textSize="16sp"
        android:gravity="center_vertical"/>

3.然后我们便创建一个实体类,把列表里所需要的一些变量的定义出来并创建方法
Daily:

public class Daily {
    private int categoryId;

    public Daily(int categoryId, int classifyId, String classifyName) {
        this.categoryId = categoryId;
        this.classifyId = classifyId;
        this.classifyName = classifyName;
    }

    public int getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }

    public int getClassifyId() {
        return classifyId;
    }

    public void setClassifyId(int classifyId) {
        this.classifyId = classifyId;
    }

    public String getClassifyName() {
        return classifyName;
    }

    public void setClassifyName(String classifyName) {
        this.classifyName = classifyName;
    }

    private int classifyId;
    private String classifyName;
}

3.接着便是创建出一个适配器,用来更新列表
DailyAdapter:

public class DailyAdapter extends BaseAdapter {
    private Context context;
    private List<Daily> dailyList;

    public DailyAdapter(Context context, List<Daily> dailyList) {
        this.context = context;
        this.dailyList = dailyList;
    }

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

    @Override
    public Object getItem(int i) {
        return dailyList.get(i);
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {

        View v= LayoutInflater.from(context).inflate(R.layout.daily_item,null);

        TextView tv=v.findViewById(R.id.daily_item_tv);
        tv.setText(dailyList.get(i).getClassifyName());
        return v;
    }
}

4.再然后就是回到DailyActivity里,来进行Http请求、JSON解析,以及引进实体类和在里面绑定适配器

public class DailyActivity extends AppCompatActivity {
    private ListView dailyListView;
    private List<Daily>dailyList=new ArrayList<>();
    private String api="http://103.244.59.105:8014/paopaoserver/articles?params={\"page\":1,\"page_count\":10}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_daily);

        dailyListView=findViewById(R.id.daily_listview);
        new DailyTask().execute();

        dailyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent(DailyActivity.this,GoodsActivity.class);
                int classifyId=dailyList.get(i).getClassifyId();
                intent.putExtra("id",classifyId);//传值
                startActivity(intent);
            }
        });


    }
    class DailyTask extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... strings) {
            StringBuffer stringBuffer=new StringBuffer();
            try {
                URL url=new URL(api);
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                InputStream inputStream=null;
                if(httpURLConnection.getResponseCode()==200){
                    inputStream=httpURLConnection.getInputStream();
                }else {
                    return "network-failed";  //网络连接失败
                }

                InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
                BufferedReader bufferedReader=new BufferedReader(inputStreamReader);


                String temp="";
                while ((temp=bufferedReader.readLine())!=null){
                    stringBuffer.append(temp);
                }
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return stringBuffer.toString();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                JSONObject object=new JSONObject(s);
                JSONArray array=object.getJSONArray("datas");

                for(int i=0;i<array.length();i++){
                    JSONObject obj=array.getJSONObject(i);

                    Daily daily=new Daily(obj.getInt("category_id"),obj.getInt("classify_id"),obj.getString("classify_name"));
                    dailyList.add(daily);//导入列表
                }
                DailyAdapter adapter=new DailyAdapter(DailyActivity.this,dailyList);
                dailyListView.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }
}

三、第三部分:然后就是从具体的每一列跳转进具体的页面,效果图如下:
效果图:
这里写图片描述
第三部分的步骤大多和第二部分的步骤一样,只是新增了一个从网上获取相对应图片的代码
1.因为要更新图片,所以要在适配器里进行相应的操作。首先把获取图片的网站先定义好

String img_url="http://103.244.59.105:8014/paopaoserver"+goods.getSmallPic();

2.然后就是新建一个ImgTask方法来继承AsyncTask方法,在里面进行http请求的操作

  class ImgTask extends AsyncTask<String,String,Integer>{
        private ImageView imageView;

        public ImgTask(ImageView imageView) {
            this.imageView = imageView;
        }

        private Bitmap bmp;

        @Override
        protected Integer doInBackground(String... strings) {
            try {
                URL url=new URL(strings[0]);
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                InputStream inputStream=null;
                if(httpURLConnection.getResponseCode()!=200){
                    return -1;
                }
                inputStream=httpURLConnection.getInputStream();
                bmp= BitmapFactory.decodeStream(inputStream);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            imageView.setImageBitmap(bmp);
        }
    }

3.然后再启动ImgTask方法,要注意的是图片要批量下载即用executeOnExecutor方法,这样更快

 new ImgTask(imageView).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,img_url);

4.整体代码如下
实体类 Goods

public class Goods {
    private String categoryName;

    public String getCategoryName() {
        return categoryName;
    }

    public Goods(String categoryName, int classifyId, String classifyName, int counties, double nowPrice, double oldPrice, int productId, String productName, String smallPic) {
        this.categoryName = categoryName;
        this.classifyId = classifyId;
        this.classifyName = classifyName;
        this.counties = counties;
        this.nowPrice = nowPrice;
        this.oldPrice = oldPrice;
        this.productId = productId;
        this.productName = productName;
        this.smallPic = smallPic;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public int getClassifyId() {
        return classifyId;
    }

    public void setClassifyId(int classifyId) {
        this.classifyId = classifyId;
    }

    public String getClassifyName() {
        return classifyName;
    }

    public void setClassifyName(String classifyName) {
        this.classifyName = classifyName;
    }

    public int getCounties() {
        return counties;
    }

    public void setCounties(int counties) {
        this.counties = counties;
    }

    public double getNowPrice() {
        return nowPrice;
    }

    public void setNowPrice(double nowPrice) {
        this.nowPrice = nowPrice;
    }

    public double getOldPrice() {
        return oldPrice;
    }

    public void setOldPrice(double oldPrice) {
        this.oldPrice = oldPrice;
    }

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public String getSmallPic() {
        return smallPic;
    }

    public void setSmallPic(String smallPic) {
        this.smallPic = smallPic;
    }

    private int classifyId;
    private String classifyName;
    private int counties;
    private double nowPrice;
    private double oldPrice;
    private int productId;
    private String productName;
    private String smallPic;
}

适配器 GoodsAdapter

public class GoodsAdapter extends BaseAdapter {
    private Context context;
    private List<Goods> goodsList;

    public GoodsAdapter(Context context, List<Goods> goodsList) {
        this.context = context;
        this.goodsList = goodsList;
    }


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

    @Override
    public Object getItem(int i) {
        return goodsList.get(i);
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v= LayoutInflater.from(context).inflate(R.layout.goods_item,null);

        ImageView imageView=v.findViewById(R.id.goods_item_iv);
        TextView titleTV=v.findViewById(R.id.goods_item_title);
        TextView typeTV=v.findViewById(R.id.goods_item_type);
        TextView priceTV=v.findViewById(R.id.goods_item_price);
        Button buyBtn=v.findViewById(R.id.goods_item_buy_btn);

        Goods goods=goodsList.get(i);
        titleTV.setText(goods.getProductName());
        typeTV.setText(goods.getCategoryName()+"-"+goods.getClassifyName());
        priceTV.setText( goods.getNowPrice()+"");

        String img_url="http://103.244.59.105:8014/paopaoserver"+goods.getSmallPic();

        new ImgTask(imageView).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,img_url);

        return v;
    }
    class ImgTask extends AsyncTask<String,String,Integer>{
        private ImageView imageView;

        public ImgTask(ImageView imageView) {
            this.imageView = imageView;
        }

        private Bitmap bmp;

        @Override
        protected Integer doInBackground(String... strings) {
            try {
                URL url=new URL(strings[0]);
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                InputStream inputStream=null;
                if(httpURLConnection.getResponseCode()!=200){
                    return -1;
                }
                inputStream=httpURLConnection.getInputStream();
                bmp= BitmapFactory.decodeStream(inputStream);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            imageView.setImageBitmap(bmp);
        }
    }
}

主体类 GoodsActivity

public class GoodsActivity extends AppCompatActivity {
    private List<Goods> goodsList=new ArrayList<>();
    private ListView listView;
    private GoodsAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods);
        //取值--classifyId
        Intent intent=getIntent();
        int id=intent.getIntExtra("id",0);

        listView=findViewById(R.id.goods_lv);

        //构造对应类目的API
        String api="http://103.244.59.105:8014/paopaoserver/categorylist?params={\"classify_id\":"+id+",\"page\":1,\"page_count\":10}";

        new MyTask().execute(api);

    }
        class MyTask extends AsyncTask<String,String,Integer>{

        @Override
        protected Integer doInBackground(String... strings) {
            StringBuffer stringBuffer=new StringBuffer();

            try {
                URL url=new URL(strings[0]);
                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
                if(httpURLConnection.getResponseCode()!=200){
                    return -1;
                }else{
                    InputStream inputStream=httpURLConnection.getInputStream();
                    InputStreamReader inputStreamReader=new InputStreamReader(inputStream);
                    BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
                    String temp="";
                    while ((temp=bufferedReader.readLine())!=null){
                        stringBuffer.append(temp);
                    }
                    bufferedReader.close();
                    inputStreamReader.close();
                    inputStream.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                JSONObject jsonObject=new JSONObject(stringBuffer.toString());
                JSONArray array=jsonObject.getJSONArray("datas");
                for(int i=0;i<array.length();i++){
                    JSONObject jsonObject1=array.getJSONObject(i);
                    String categoryName=jsonObject1.getString("category_name");
                    int classifyId=jsonObject1.getInt("classify_id");
                    String classifyName=jsonObject1.getString("classify_name");
                    int counties=jsonObject1.getInt("counties_id");
                    double nowPrice=jsonObject1.getDouble("nowprice");
                    double oldPrice=jsonObject1.getDouble("oldprice");
                    int productId=jsonObject1.getInt("product_id");
                    String productName=jsonObject1.getString("product_name");
                    String smallPic=jsonObject1.getString("small_pic");

                    Goods goods=new Goods( categoryName,  classifyId, classifyName,  counties, nowPrice, oldPrice,  productId, productName, smallPic);
                    goodsList.add(goods);//填充List列表

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return 1;
        }

        @Override
        protected void onPostExecute(Integer s) {
            super.onPostExecute(s);
            if(s==-1){
                Toast.makeText(GoodsActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
            }else {

                adapter=new GoodsAdapter(GoodsActivity.this,goodsList);
                listView.setAdapter(adapter);

            }
        }
    }
}

最后一步:因为牵扯到权限问题,所以要在Manifest里加上一句请求

  <uses-permission android:name="android.permission.INTERNET" />

不过这只适用于安卓6.0以下版本的,6.0以上版本的可以参考我前几篇的所说的解决方法,笔芯!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值