Android网络请求之HttpUrlConnection+Handler用法

 Apache接口(org.appache.http)----HttpClient<--点这,使用起来更方面更强大。一般来说,用这种接口。不过本文还是把第一种接口过一下。    

任何一种接口,无外乎四个基本功能:访问网页、下载图片或文件、上传文件.本文示范的是访问网页和下载图片。HttpURLConnection继承自URLConnection类,用它可以发送和接口任何类型和长度的数据,且预先不用知道数据流的长度,可以设置请求方式get或post、超时时间。

 

切记加网络权限<uses-permission android:name="android.permission.INTERNET" />



public class MainActivity extends AppCompatActivity {

    private ImageView imageView;
    private String path;
    private ListView listView;

    /**
     *在主线程中不能做耗时操作,只能在子线程完成
     * 在子线程中不能做UI更新,只能在主线程完成
     */
    @SuppressLint("HandlerLeak")
    Handler  handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    Bitmap bitmap= (Bitmap) msg.obj;
                    imageView.setImageBitmap(bitmap);
                    break;
                case 1:
                   String json= (String) msg.obj;
                    //Log.i("xxx", json);
                    Gson gson = new Gson();
                    //解析json
                    JsonBean jsonBean = gson.fromJson(json, JsonBean.class);
                    Log.i("xxx", jsonBean.toString());
                    ArrayList<Datas> date = jsonBean.getData();
                    listView.setAdapter(new MyAdapter(date,MainActivity.this));
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //找控件
        imageView = findViewById(R.id.img);
        listView = findViewById(R.id.listview);
         //方法
        getImage();//获取图片
        getJsonData();//获取json
    }
    //获取json方法
    private void getJsonData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = "http://120.27.23.105/ad/getAd";
                try {
                    //设置url
                    URL url = new URL(path);
                    //开启连接
                   HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                   //设置请求方式
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5000);
                    //获取请求码
                    int code = connection.getResponseCode();
                    //判断网络连接
                    if (code == HttpURLConnection.HTTP_OK){
                        //获取服务器资源
                        InputStream inputStream = connection.getInputStream();
                        //输入流转输出流
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                       byte[] buffer = new byte[1024];
                       int len = 0;
                       while ((len=inputStream.read(buffer))!=-1){
                           bos.write(buffer,0,len);
                       }
                        inputStream.close();
                       bos.close();
                       String json = bos.toString();
                        Message message = new Message();
                        message.what=1;
                        message.obj = json;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    //获取image方法
    private void getImage() {
        //设置url
        path = "http://gbres.dfcfw.com/Files/picture/20170306/size500/9FEA9AB789FA665C3418A84E561F3FCB.jpg";
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    //开启链接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //请求方式
                    connection.setRequestMethod("GET");
                    //获取请求码
                    int code = connection.getResponseCode();
                    //判断是
                    // 否请求成功
                    if (code==HttpURLConnection.HTTP_OK){
                        //获取服务器资源
                        InputStream inputStream = connection.getInputStream();
                        //图片资源给控件
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        //创建消息
                        Message message = new Message();
                        message.obj = bitmap;
                        message.what=0;
                        //发送消息
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }
}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用HTTPURLConnection发送请求,可以按照以下步骤进行: 1. 在AndroidManifest.xml文件中添加网络权限: ``` <uses-permission android:name="android.permission.INTERNET" /> ``` 2. 在子线程中使用HTTPURLConnection发送请求,例如: ``` Thread thread = new Thread(new Runnable() { @Override public void run() { try { // 创建URL对象 URL url = new URL("http://www.example.com/api"); // 打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法 connection.setRequestMethod("GET"); // 设置连接超时和读取超时时间 connection.setConnectTimeout(5000); connection.setReadTimeout(5000); // 发送请求 connection.connect(); // 获取响应码 int responseCode = connection.getResponseCode(); // 获取响应数据 InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); inputStream.close(); String responseData = response.toString(); // 处理响应数据 } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); ``` 这个例子中发送了一个GET请求,获取了http://www.example.com/api的响应数据。你可以根据需要设置请求方法、请求参数、请求头等。获取响应数据后,可以在UI线程中更新UI或者在子线程中处理响应数据。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值