网络请求----简单框架使用------(百度图片下载实例)

1,Net网络请求类

package com.example.mylibrary;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;


/**
 * Created by alien on 2015/4/9.
 */
public class Net {
    static Net instance;
    private Net(){};
    public static Net getInstance(){
        if(instance==null){
            instance=new Net();
        }
        return instance;
    }

    public interface CallBack{
        void onCallBack(String result);
    }
    public interface BitmapCallBack{
        void onBitmapCallBack(Bitmap bitmap);
    }


    //get请求:这里的请求参数必须写在string url里面,通过URL realurl=new URL(url);来访问地址
    public void netGet(final String url ,final Map<String,String> params,final CallBack callBack){
        final Handler handler=new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String requestData="";
                    if(params==null){
                        requestData=url;
                    }
                    if(params!=null){
                        requestData=url+"?";
                        for(Entry<String,String> entry:params.entrySet()){
                            requestData+=URLEncoder.encode(entry.getKey(),"UTF-8")+
                                    "="+URLEncoder.encode(entry.getValue(),"UTF-8")+"&";
                        }

                    }
                    URL realurl=new URL(requestData);
                    HttpURLConnection connection= (HttpURLConnection) realurl.openConnection();
                    //貌似默认的是get请求
                    connection.setRequestMethod("GET");
                    //获取输入流(inputstream和outputstream是其他字节流的父类(抽象类)是不能直接new的
                    // 必须继承他,实例化它的子类)
                    InputStream in=connection.getInputStream();
                    ByteArrayOutputStream out=new ByteArrayOutputStream();
                    int a=0;
                    byte[] bytes=new byte[1024*20];
                    while ((a=in.read(bytes))!=-1){
                            out.write(bytes,0,a);
                    }
                    in.close();
                    out.flush();
                    out.close();
                    //toByteArray:返回这个流的当前内容作为一个字节数组。
                    final String result=new String(out.toByteArray());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            callBack.onCallBack(result);
                        }
                    });

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();


    }

    //post请求,这里的请求参数需要方法对应的输出流里面去请求网络(httpurlconnection)对应的outputstream

    public void netPost(final String url, final Map<String,String> params, final CallBack callBack){
        final Handler handler=new Handler();
        new Thread(new Runnable() {

            @Override
            public void run() {
                try{
                    InputStream in = null;
                    URL realurl = null;
                    String result = null;
                    String requestData="";
                    HttpURLConnection conn = null;
                    realurl = new URL(url);
                    conn = (HttpURLConnection)realurl.openConnection();
                    //post请求必须设置为true这下面的两个
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setRequestMethod("POST");

                    if(params!=null){
                        for(Entry<String,String> entry:params.entrySet()){
                                requestData+= "&"+
                                        URLEncoder.encode(entry.getKey(),"UTF-8")
                                        +"="
                                        + URLEncoder.encode(entry.getValue(),"UTF-8");
                        }
                    }
                    //取出网络对应的输出流,这里转化为了字符流
                    PrintWriter pw = new PrintWriter(conn.getOutputStream());
                    pw.print(requestData);
                    pw.flush();
                    pw.close();
//                    //这里也可以不转化为字符流,直接写出字节流
//                    OutputStream out=conn.getOutputStream();
//                    out.write(requestData.getBytes());
                    //获取对应的输入流,然后取到返回的数据
                    in = conn.getInputStream();
                    BufferedReader bin = new BufferedReader(
                            new InputStreamReader(in));
                    String line;
                    while ((line = bin.readLine()) != null) {
                        result += line;
                    }
                    in.close();
                    final String finalResult = result;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            //这里通过回调去处理返回的数据
                            callBack.onCallBack(finalResult);
                        }
                    });

                }catch(Exception eio){
                    eio.printStackTrace();
                }
            }
        }).start();

    }

    public void netBitmap(final String url, final BitmapCallBack callBack){
        final Handler handler=new Handler();
        new Thread(new Runnable() {
                @Override
                public void run() {
                    URL realurl = null;
                    try {
                        realurl = new URL(url);
                        HttpURLConnection connection = (HttpURLConnection) realurl.openConnection();
                        //貌似默认的是get请求
                        connection.setRequestMethod("GET");
                        connection.setDoInput(true);
                        connection.connect();
                        //获取输入流(inputstream和outputstream是其他字节流的父类(抽象类)是不能直接new的
                        // 必须继承他,实例化它的子类)
                        InputStream in = connection.getInputStream();
                        final Bitmap bitmap = BitmapFactory.decodeStream(in);
                        in.close();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                callBack.onBitmapCallBack(bitmap);
                            }
                        });
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (ProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                }).start();

        }

}

2,百度的图片的获取

package com.example.downloadimg;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.mylibrary.Net;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by alien on 2015/4/10.
 */
public class SearchImgActivity extends ActionBarActivity{
    private RecyclerView mRecyclerView;
    private EditText searchkey;
    private ImageView img;
    private List<ResponseData> responseDataList=new ArrayList<>();
    private MyAdapter adapter=new MyAdapter();
    private String url;
    private int page=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.searchimg_activity);

        initview();
        mRecyclerView.setAdapter(adapter);

        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page=0;
                responseDataList.removeAll(responseDataList);
                requestData();
            }
        });

    }

    private void initview(){
        mRecyclerView= (RecyclerView) findViewById(R.id.recyclerview);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        searchkey= (EditText) findViewById(R.id.search_key);
        img= (ImageView) findViewById(R.id.img_search);
    }

    public void requestData(){
        try {
            String word=URLEncoder.encode(searchkey.getText().toString(),"GBK");
            url="http://image.baidu.com/i?tn=resultjson_com&word="+word+"&rn=10&pn="+page*20;
            Log.i("test","url------------"+url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Net.getInstance().netGet(url,null,new Net.CallBack() {
            @Override
            public void onCallBack(String result) {

                Log.i("test",result);
                Gson gson=new Gson();
                Data datas=gson.fromJson(result,Data.class);
                Log.i("test","数组------"+datas.data.length);
                if(datas!=null){
                    for(int i=0;i<datas.data.length;i++){
                        ResponseData responseData=datas.data[i];
                        responseDataList.add(responseData);
                    }
                }
            }
        });
    }



    class MyAdapter extends RecyclerView.Adapter{

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
            LayoutInflater inflater=LayoutInflater.from(SearchImgActivity.this);
            View item=inflater.inflate(R.layout.recyclerview_img,viewGroup,false);
            ImageViewHolder holder=new ImageViewHolder(item);
            return holder;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
            ((ImageViewHolder)viewHolder).setData(responseDataList.get(position));
            if((position+1)%11==0){
                page++;
                requestData();
                Log.i("test","page-----"+page);
            }
            Log.i("test","position------"+position);
        }

        @Override
        public int getItemCount() {
            Log.i("test","长度---"+responseDataList.size()+"");
            return responseDataList.size();
        }


        class ImageViewHolder extends RecyclerView.ViewHolder{
            private ImageView item_img;
            WindowManager manager= (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            final int width=manager.getDefaultDisplay().getWidth();
            public ImageViewHolder(View itemView) {
                super(itemView);
                item_img= (ImageView) itemView.findViewById(R.id.item_img);


            }
            public void setData(final ResponseData data){
                float percentage=(float)data.height/data.width;
                item_img.setLayoutParams(new LinearLayout.LayoutParams(width/2,(int) (percentage*width/2)));
                item_img.setImageBitmap(null);
                Net.getInstance().netBitmap(data.thumbURL,new Net.BitmapCallBack() {

                    @Override
                    public void onBitmapCallBack(Bitmap bitmap) {
                        item_img.setImageBitmap(bitmap);

                    }
                });
            }
        }
    }


    //json解析数据格式
    private class ResponseData{

        private String fromPageTitle,type,filesize,currentIndex,thumbURL;
        private int width,height,pageNum;

        public ResponseData(String fromPageTitle,String type,String currentIndex,String thumbURL,
                            String filesize, int pageNum ,int width,int height
        ){
            this.thumbURL=thumbURL;
            this.currentIndex=currentIndex;
            this.filesize=filesize;
            this.fromPageTitle=fromPageTitle;
            this.height=height;
            this.width=width;
            this.pageNum=pageNum;
            this.type=type;
        }

    }
    private class Data{
        private ResponseData[] data;
        public Data(ResponseData[] data){
            this.data=data;
        }
    }


}

这里用了recyclerview的serlayoutmanager,布局管理器是:new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
百度图片的接口:http://image.baidu.com/i?tn=resultjson_com&word=“+word+”&rn=10&pn=”+page*20

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值