【小王的安卓之路】Android原生网络请求

Android原生网络请求

一. 网络请求的必要性

二. 网络请求分类

三. 网络请求实现方法

四. 注意事项

一.网络请求的必要性:
如今单机APP早已经接近消失就连最简单的时钟日期等软件都需要去请求网络来完成同步。我们在制作一个APP时连接网络几乎成了一个必要的条件。

二.网络请求分类:
网络请求主要分为两类:

GET请求: 将请求及其参数追加到url后面来实现请求,主要用来请求数据

POST请求:只发送请求,参数或者其他文件用包的形式单独传递,主要用来提交数据

三.网络请求实现方法

3.1 GET请求

private void requestByGet() {
    try {
        URL url = new URL("此处写入你想要请求的url");
        HttpURLConnection connection =(HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(30*1000);//设置超时时长,单位ms
        connection.setRequestMethod("GET");//设置请求格式
        connection.setRequestProperty("Content-Type","Application/json");//期望返回的数据格式
        connection.setRequestProperty("CharSet","UTF-8");//设置字符集
        connection.setRequestProperty("Accept-CharSet","UTF-8");//请求的字符集
        connection.connect();//发送请求

        int responseCode =connection.getResponseCode();//获取返回码
        String responseMessage = connection.getResponseMessage();//获取返回信息
        if(responseCode==HttpURLConnection.HTTP_OK)//请求成功操作
        {
        //TODO 
          
            }

        runOnUiThread(new Runnable() //TODO 执行更新UI操作
         {
            @Override
            public void run() {
            
            }
        });
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

3.2 post请求

private void requestByPost(final TextView showText) {
   try {
        URL url = new URL("此处写入你想要请求的url");
        HttpURLConnection connection =(HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(30*1000);//设置超时时长,单位ms
        connection.setRequestMethod("GET");//设置请求格式
        connection.setRequestProperty("Content-Type","Application/json");//期望返回的数据格式
        connection.setRequestProperty("CharSet","UTF-8");//设置字符集
        connection.setRequestProperty("Accept-CharSet","UTF-8");//请求的字符集
      
        connection.setUseCaches(false);//设置缓存使用
        connection.setDoInput(true);//设置输入流使用
        connection.setDoOutput(true);//设置输出流使用
        connection.connect();

        String data = "username=" + getEncodeValue("小王") + "&number="+getEncodeValue("123456");
        OutputStream outputStream = connection.getOutputStream();//获取到输出流
        outputStream.write(data.getBytes());//写入数据
        outputStream.flush();//执行
        outputStream.close();//关闭

        int responseCode =connection.getResponseCode();
        String responseMessage = connection.getResponseMessage();
        if(responseCode==HttpURLConnection.HTTP_OK)
        {
          //TODO
                  }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
              
            }
        });
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

四.注意事项
1.进行网络请求需要申请权限,可以是动态的也可以是静态的,这里我们使用静态的。将这句话写在标签上方即可

<uses-permission android:name="android.permission.INTERNET"/>

2.进行网络请求属于耗时操作,应该放在子线程执行。

readButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                requestByGet(showText);

            }
        }).start();

    }
});

3.有时候使用post请求时,你的参数可能不是UTF-8型就会出现乱码。要将参数进行转化。

private String getEncodeValue(String name)
{
    String encode = null;

    try {
       encode= URLEncoder.encode(name,"UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return encode;
}

小结:

虽然现在我们有很多的网络请求框架如OKhttp等,但熟悉原生的网络请求方法也是很有必要的。如果有不对的地方恳请指正!

发布了47 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_41525021/article/details/98044321
今日推荐