HttpUrlConnection网络请求,图片+文字

//工具类



package com.wzq.urlcondemo.utils;



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


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;


/**
 * author:Created by WangZhiQiang on 2017-10-31.
 * 请求网络工具类;
 */


public class NetUtil {
    private static String tag = "getNetJson";


    public static String getNetJson(String urlString) {
        try {
            //把接口地址封装到URL对象中;
            URL url = new URL(urlString);
            //使用HttpURLConnection, HttpURLConnection是URLConnection的子类;
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(8000);
            //200代表请求数据成功
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 200) {
                InputStream inputStream = urlConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String temp="";
                StringBuilder stringBuilder = new StringBuilder();


                while((temp = bufferedReader.readLine()) != null) {
                    stringBuilder.append(temp);
                }
                String result = stringBuilder.toString();
                return result;


            }else {
                //do nothing
            }


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


    /**
     * 获取网络图片
     *
     * @param urlString
     * @return
     */
    public static Bitmap getNetBitmap(String urlString) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection httpurlConnection = (HttpURLConnection) url.openConnection();
            httpurlConnection.setConnectTimeout(8000);//设置链接超时时间
            int responseCode = httpurlConnection.getResponseCode();


            if (responseCode == 200) {
                InputStream inputStream = httpurlConnection.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return  bitmap;


            } else {
                //do nothing
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.e(tag, "getNetBitmap: " + e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(tag, "getNetBitmap: " + e.toString());
        }
        return null;
    }


}




主页面

package com.wzq.urlcondemo;


import android.annotation.SuppressLint;
import android.graphics.Bitmap;
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.ImageView;
import android.widget.TextView;


import com.wzq.urlcondemo.utils.NetUtil;


/**
 * 主线程 ---UI线程,不可以阻塞, 如果阻塞会报ANR(application not response)
 * 子线程---, 耗时操作,联网就是耗时操作;
 *
 * 1--控件
 * 2--点击事件
 * 3---请求网络
 * 4 借助handler更新UI;
 */
public class MainActivity extends AppCompatActivity {


    public String urlString = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1";
    String urlBitmap = "https://img-my.csdn.net/uploads/201407/26/1406383265_8550.jpg";
    String tag = "wzq";
    private ImageView iv;
    private TextView tv;
    //定义一个handler,用来更新UI;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            if (what == 0) { //发送的文字
                tv.setText((String)msg.obj);
            }else if(what == 1){ //发送的是图片;
                iv.setImageBitmap((Bitmap) msg.obj);
            }
        }
    };


    /**
     * alt+enter  自动补全
     * fbc --再tabfindViewByIde的快捷键;
     * ctrl+alt +F 声明全局变量
     * ctrl+alt +L  格式化代码
     * ctro+p 参数提示
     * f2 --定位代码错误位置
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);
        iv = (ImageView) findViewById(R.id.iv);
        setOnClickListener();


    }
    //设置监听
    private void setOnClickListener() {
        //文字的点击事件
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        //得到从服务器请求的json数据;
                        String json = NetUtil.getNetJson(urlString);
                        Message message = new Message();
                        message.what = 0;//代表发送的是文字;
                        message.obj = json;
                        handler.sendMessage(message);




                    }
                }.start();
            }
        });


        //图片的点击事件
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap netBitmap = NetUtil.getNetBitmap(urlBitmap);
                        //获取message
                        Message message = Message.obtain();
                        message.what =1;//代表是发送图片的标记位;
                        message.obj = netBitmap;
                        handler.sendMessage(message);
                    }
                }).start();
            }
        });


    }




}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值