Android的网络编程

Android的网络编程





一、网络访问httpconnection

二、网络框架





一、网络访问httpconnection

⭐️在网络编程前,首先要在AndroidManifest.xml的application标签增加以下属性:
<uses-permission android:name="android.permission.INTERNET" /> 用来允许网络操作的执行。

  • 将url字符串转为url对象
  • 获得httpconnection对象
  • 设置连接相关参数
  • 配置证书
  • 进行数据的读取,首先判断响应码是否为200

1.将url字符串转为url对象

URL url = new URL(urlPath);

2.获得httpconnection对象

connection = (HttpURLConnection) url.openConnection();

3.设置连接相关参数

connection.setRequestMethod("GET");//默认为get
            connection.setUseCaches(false);//不使用缓存
            connection.setConnectTimeout(15000);//设置连接超时时间
            connection.setReadTimeout(15000);//设置读取超时时间
            connection.setRequestProperty("Connection","Keep-Alive");//设置请求头参数
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:70.0) Gecko/20100101 F

4.配置证书

if ("https".equalsIgnoreCase(url.getProtocol())){
                ((HttpsURLConnection)connection).setSSLSocketFactory(HttpsUtil.getSSLSocketFactory());
            }

getSSLSocketFactory()方法

 //获取这个SSLSocketFactory
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

5.进行数据的读取,首先判断响应码是否为200

//5.进行数据的读取,首先判断响应码是否为200
            if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK){
                //获得输入流
                is = connection.getInputStream();
                //包装字节流为字符流
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                //读取数据
                StringBuffer response = new StringBuffer();
                String line;

                while ((line = reader.readLine())!= null){
                    response.append(line);
                }
                //关闭资源
                is.close();
                connection.disconnect();
                //返回
                return response.toString();
            }






二、网络框架




  • 图片框架glide
  • okhttp

1.图片框架glide
(1)导入依赖包

implementation 'com.github.bumptech.glide:glide:4.10.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
    implementation 'com.github.bumptech.glide:okhttp3-integration:4.10.0'

(2)直接使用即可

              Glide.with(this).load("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2363799301,1741488617&fm=26&gp=0.jpg").into(imageView);



2.okhttp请求

(1)构造Request

Request request = new Request.Builder().url(url)
                .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:70.0) Gecko/20100101 Firefox/70.0")
                .addHeader("Accept", "application/json")
                .get()
                .method("GET", null)
                .build();

(2)发送请求,并处理回调

 OkHttpClient client = HttpsUtil.handleSSLHandshakeByOkHttp();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //获得响应主体的json字符串
                String json = response.body().string();
                //使用fastjson库解析json字符串
                final Ip ip = JSON.parseObject(json, Ip.class);
                //回到UI线程显示获取的数据
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //根据返回的code判断是否成功
                        if (ip.getCode() != 0) {
                            textView.setText("请求失败无数据");
                        } else {
                            //解析数据
                            IpData data = ip.getData();
                            textView.setText(data.getRegion()+","+data.getCity()+",,,,,,"+data.getArea());
                        }

                    }
                });

            }
        });
发布了11 篇原创文章 · 获赞 8 · 访问量 912

猜你喜欢

转载自blog.csdn.net/qq_44739668/article/details/103004590
今日推荐