栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

第五章:Android开发之联网

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

第五章:Android开发之联网

联网 常用的网络请求

1、OKhttp     常用
2、retrofit     常用
3、volley       常用
4、XUtils        偶尔
5、HttpURLConnection   不常用
6、HttpClient                    不常用

HttpUrlConnect—Get 步骤:

 需要

1、创建URL对象
     URL url = new URL(path);
2、利用url的openConnection方法返回HttpUrlConnection对象
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
3、设置请求方式
     connection.setRequestMethod("GET");


4、设置连接超时
     connection.setConnectTimeout(5 * 1000);
5、获得返回的输入流
      InputStream inputStream = connection.getInputStream();
6、关闭连接
     connection.disconnection();

String path = "http://49.232.114.172:8080/yunying/qufumanage/getList.json";
        try {
            URL url = new URL(path);
            //获得httpUrlConnection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置请求的方式为get
            connection.setRequestMethod("GET");
            //设置连接的时间为5秒
            connection.setConnectTimeout(5 * 1000);
            //如果responseCode=200时
            if (connection.getResponseCode() == 200) {
                //获取输入流
                InputStream inputStream = connection.getInputStream();
            }

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

把输入流转化成String

1、创建ByteArrayOutputStream对象
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
2、创建byte[]和int len
      byte[] bytes = new byte[1024];
      int len = 0;
3、将输入流读到byte[]字节数组里
       while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
4、关闭流和链接

流转字符串


1、创建ByteArrayOutputStream对象
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
2、创建byte[]和int len
      byte[] bytes = new byte[1024];
      int len = 0;
3、将输入流读到byte[]字节数组里
       while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
4、关闭流和链接

               ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int len = 0;
                //将输入流读到byte[]字节数组里
                while ((len = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, len);
                }
                outputStream.close();
                 connection.disconnect();
                return new String(outputStream.toByteArray());

HttpURLConnection—POST

“http://49.232.114.172:8080/yunying/qufumanage/login.php”      
1、创建URL对象
     URL url = new URL(path);
2、利用url的openConnection方法返回HttpUrlConnection对象
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
3、设置请求方式
     connection.setRequestMethod("POST");

String data = "username="+ URLEncoder.encode("root","UTF-8")
                    +"&password="+URLEncoder.encode("root123456","UTF-8");

OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(data.getBytes());
//刷新此输出流并写出所有的输出字节
outputStream.flush();

            InputStream inputStream = httpURLConnection.getInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int lent = 0;
            while ((lent =inputStream.read(bytes)) != -1){
                output.write(bytes,0,lent);
            }
            String ss  = new String(output.toByteArray());

            outputStream.close();
            output.close();
            inputStream.close();
            httpURLConnection.disconnect();


HttpUrlConnect

android.os.NetworkOnMainThreadException
在Android 4.0以上,网络连接不能放在主线程上,不然就会报错android.os.NetworkOnMainThreadException。但是4.0下版本可以不会报错。

解决办法——创建子线程

    new Thread(new Runnable() {
                    @Override
                    public void run() {
                        
                    }
                }).start();


HttpClient

一、gradle配置文件中

android{
            defaultConfig{
                  useLibrary "org.apache.http.legacy"
                   }
       }


 

HttpClient—POST

一、gradle配置文件中

android{
            defaultConfig{
                  useLibrary "org.apache.http.legacy"
                   }
       }


 

HttpClient = Get

 private void getHttpClient(){
        HttpClient client = new DefaultHttpClient(); //获取HttpClient对象
        String url = "http://49.232.114.172:8080/yunying/qufumanage/login.php";
        HttpGet httpGet = new HttpGet(url);  //获取httpget对象
        try {
            HttpResponse response = client.execute(httpGet);//执行后返回HttpResponse
            HttpEntity entity = response.getEntity();
            String string = EntityUtils.toString(entity,"UTF-8");
            Log.d("TAG", "string==" + string);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    异常:android.os.NetworkOnMainThreadException

     new Thread(new Runnable() {
                    @Override
                    public void run() {
                        
                    }
                }).start();

HttpClient = POST

        String path = "http://49.232.114.172:8080/yunying/qufumanage/login.php";
        HttpClient httpClient = new DefaultHttpClient(); //获取httpClient对象
        HttpPost httpPost = new HttpPost(path); //获取HttpPost对象
        List pairs = new ArrayList<>();  //添加参数
        pairs.add(new BasicNamevaluePair("username","root"));
        pairs.add(new BasicNamevaluePair("password","root123456"));

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8)); //获得实体
            HttpResponse execute = httpClient.execute(httpPost); //执行请求
            String s = EntityUtils.toString(execute.getEntity()); //把内容转换成String
            Log.d("TAG",s);

        }  catch (Exception e) {
            e.printStackTrace();
        }


 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/770594.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号