HttpClient网络请求获取网络图片

来源:互联网 发布:淘宝网上怎么看正品 编辑:程序博客网 时间:2024/05/16 07:22

适配器:Myadapter

package com.bawi.adapter;


import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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.bawi.Bean.Bean;
import com.bawi.httpclient_lx.R;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class Myadapter extends BaseAdapter{

    private Activity context;
    private ArrayList<Bean> bean;
    public static final String IMAGEURL="http://09.imgmini.eastday.com/mobile/20170808/20170808170806_eee032606496949d92efbc906c7140dd_2_mwpm_03200403.jpg";

    public Myadapter(Activity context, ArrayList<Bean> bean) {

        this.context=context;
        this.bean=bean;

    }

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

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

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

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

        ViewHolder holder=null;
        if(converView==null)
        {
            converView= LayoutInflater.from(context).inflate(R.layout.item_lv, null);
            holder=new ViewHolder();
            holder.tv_title= (TextView) converView.findViewById(R.id.tv_title);
            holder.tv_category= (TextView) converView.findViewById(R.id.tv_category);
            holder.tv_data= (TextView) converView.findViewById(R.id.tv_data);
            holder.tv_image=(ImageView) converView.findViewById(R.id.tv_image);
            converView.setTag(holder);
        }else
        {
            holder= (ViewHolder) converView.getTag();
        }

        final ViewHolder finalHolder = holder;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url=new URL(bean.get(i).thumbnail_pic_s);
                    HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                    connection.connect();
                    final  InputStream inputStream=connection.getInputStream();
                    final Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            finalHolder.tv_image.setImageBitmap(bitmap);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }).start();


        holder.tv_title.setText(bean.get(i).title);
        holder.tv_category.setText(bean.get(i).category);
        holder.tv_data.setText(bean.get(i).date);

        return converView;
    }

    public class ViewHolder
    {
        public TextView tv_title,tv_category,tv_data;
        public ImageView tv_image;
    }

}


Bean类

package com.bawi.Bean;


public class Bean {

    public String url;
    public String title;
    public String date;
    public String category;
    public String author_name;
    public String thumbnail_pic_s;


}


主界面:MainActivity

package com.bawi.httpclient_lx;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.bawi.Bean.Bean;
import com.bawi.adapter.Myadapter;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ImageView tv_image;
    private String responsemsg;
    private Myadapter ma;
    private ListView lv;
    private ArrayList<Bean> list;
    private final int SUCCESS=0;
    private final int FALT=-1;
    private final String GETURL="http://v.juhe.cn/toutiao/index?type=top&&key=22a108244dbb8d1f49967cd74a0c144d";


    Handler myhandler=new Handler() {
        public void handleMessage(Message msg){
               int what = msg.what;
                switch (what){
                    case SUCCESS:
                       String result = (String) msg.obj;
                        Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
                        pareseDATA(result);
                        break;
                    case FALT:
                        Toast.makeText(MainActivity.this,responsemsg,Toast.LENGTH_SHORT).show();
                        break;
                }
        }
    };

    //JSON解析
    private void pareseDATA(String result) {

        try {
            JSONObject obj=new JSONObject(result);
            JSONObject resultobj = obj.getJSONObject("result");
            JSONArray dataArray = resultobj.getJSONArray("data");
            if(dataArray.length()>0&&dataArray!=null)
            {
                for (int i = 0; i <dataArray.length() ; i++) {
                    JSONObject data= (JSONObject) dataArray.get(i);
                    Bean bean=new Bean();
                    bean.title= data.getString("title");
                    bean.date=data.getString("date");
                    bean.thumbnail_pic_s=data.getString("thumbnail_pic_s");
                    bean.category=data.getString("category");
                    bean.url=data.optString("url");
                    list.add(bean);
                }

                System.out.println(list);
                 flushnum();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

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

        initView();
        initData();

        //创建线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                getNews();
            }
        }).start();

    }

    private void getNews() {

        StringBuffer result=new StringBuffer();
        //创建HttpClient对象,打开一个浏览器
        HttpClient httpclient = new DefaultHttpClient();

        //创建HttpGet对象,get请求对象,传入url
        HttpGet httpget=new HttpGet(GETURL);

        try {
            //发送请求,返回Httprespones对象,这是服务器返回的对象
            HttpResponse httpResponse = httpclient.execute(httpget);

            //根据相应行,拿到响应码,getStatusLine:相应行;; getStatusCode:响应码
            int responseCode = httpResponse.getStatusLine().getStatusCode();
            responsemsg = httpResponse.getStatusLine().getReasonPhrase();

            //判断响应码是否为200,如果是则请求成功否则失败
            if(200==responseCode)
            {
                //得到返回的实体对象
                HttpEntity entity = httpResponse.getEntity();
                InputStream inputStream = entity.getContent();

                BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));

                String line=null;

                while((line=reader.readLine())!=null)
                {
                    result.append(line);
                }
                Message msg=new Message();
                msg.what=SUCCESS;
                msg.obj=result.toString();
                myhandler.sendMessage(msg);

            }else
            {
                Message msg=new Message();
                msg.what=FALT;
                myhandler.sendMessage(msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            httpclient.getConnectionManager().shutdown();
        }

    }

    private void initData() {

        list=new ArrayList<Bean>();
        ma=new Myadapter(this,list);
    }

    private void flushnum()
    {
        ma=new Myadapter(this,list);
        lv.setAdapter(ma);

        lv.setOnItemClickListener(new ListView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Bean bean = (Bean) ma.getItem(i);
                Intent intent=new Intent(MainActivity.this,OtherActivity.class);
                intent.putExtra("url",bean.url);
                intent.putExtra("title",bean.title);
                startActivity(intent);
            }
        });
    }
    //初始化数据
    private void initView() {
        lv= (ListView) findViewById(R.id.lv);
    }

}


webView获取
package com.bawi.httpclient_lx;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.WebView;

public class OtherActivity extends AppCompatActivity {

    private WebView wv;
    private String title;
    private String url;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);

        initView();
        initData();

        LoadWebView();

    }


    private void initData() {
        if(getIntent().getExtras()!=null)
        {
            title = getIntent().getExtras().getString("title");
            url=getIntent().getExtras().getString("url");
            if(!TextUtils.isEmpty(title))
            {
                setTitle(title);
            }else
            {
                setTitle("详情");
            }
        }
    }

    private void LoadWebView() {

        wv.loadUrl(url);

    }
    private void initView() {
      wv= (WebView) findViewById(R.id.wv);
    }
}

主布局

<?xml version="1.0" encoding="utf-8"?>
<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" >

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

</RelativeLayout>



webView布局

<?xml version="1.0" encoding="utf-8"?>
<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"  >

    <WebView
        android:id="@+id/wv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></WebView>
</RelativeLayout>


listView布局

<?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="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
        android:id="@+id/tv_image"
        android:layout_width="80dip"
        android:layout_height="80dip"
             />

        <LinearLayout
            android:layout_gravity="center_vertical"
            android:orientation="vertical"
            android:layout_marginLeft="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/tv_title"
                android:textSize="24dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <LinearLayout
                android:layout_gravity="center_vertical"
                android:orientation="horizontal"
                android:weightSum="2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
                    <TextView
                        android:id="@+id/tv_category"
                        android:layout_weight="1"
                        android:layout_marginTop="15dp"
                        android:textSize="20dp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" />

                    <TextView
                        android:id="@+id/tv_data"
                        android:layout_weight="1"
                        android:layout_marginLeft="15dp"
                        android:layout_marginTop="15dp"
                        android:textSize="20dp"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>