Android get和post的区别

前言

在Android开发的过程中,必须会接触到数据交互(访问数据,写入数据等你等),既然接触到数据的交互,那么自然而然就是使用通讯间的协议来进行请求,最常见的协议就是Http协议,Http协议包括两个具体的请求方式Get和Post。


Http请求方式Get与Post的简介

  • 先来了解Http协议:Http(HyperText Transfer Protocol超文本传输协议)是一个设计来使客户端和服务器顺利进行通讯的协议。
  • HTTP在客户端和服务器之间以request-response protocol(请求-回复协议)工作。
  • 简单来说呢,Get与Post就是基于http协议的网络数据交互方式。

Get与Post的主要区别
          在Android开发的过程中,该如何选择Http的Get还是Post来进行通讯呢?那就详细探索他们之间的差异。
          1.get通常是从服务器上获取数据,post通常是向服务器传送数据。
          2.get是把参数数据队列加到表单的 ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到,实际上就是URL拼接方式。post是通过HTTPpost机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。
        3.对于get方式,服务器端用 Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据。
        4.get 传送的数据量较小,不能大于1KB[IE,Oher:4]。post传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。

        5.get安全性非常低,post安全性较高。Android如何使用Get与Post协议


不多说,上代码展示(演示用户登录访问服务器)
 /** * post的方式请求 
 *@param User用户名 
 *@param Password 密码 
 */
 public static  String setPostUrl(final String httpUrl, final String post) {
        String result = null;
        try {
            byte[] bs = post.getBytes();
            URL url = new URL(httpUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);//是否可写
            conn.setDoOutput(true);//是否可读
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5000);
            OutputStream os = conn.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.write(bs);
            dos.close();
            dos.flush();
            os.close();
            InputStream is = conn.getInputStream();
            //字节流转换成字符流
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            //可以拼接字符串
            StringBuffer sb = new StringBuffer();
            String str;
            char c[] = new char[8 * 1024];
            //边度编写,实现 缓冲字符流的 readLine 一行
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            result = sb.toString();

            //                        //获得结果码   优化的方式
            //                        int responseCode = conn.getResponseCode();
            //                        if(responseCode ==200){
            //                            //请求成功
            //                        }else {
            //                            //请求失败
            //                        }

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

    }
 
 
 /**     
 *get的方式请求     
 *@param username 用户名     
 *@param password 密码     
 *@return 返回null 登录异常     
 */ 
    public void startLogin() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String User = mLogin_User.getText().toString();
                    String Password = mLogin_Password.getText().toString();
                    URL url = new URL(HttpUtils.urlLogin);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);//是否可写
                    conn.setDoOutput(true);//是否可读
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    InputStream is = conn.getInputStream();
                    //字节流转换成字符流
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader br = new BufferedReader(isr);
                    //可以拼接字符串
                    StringBuffer sb = new StringBuffer();
                    String str;
                    char c[] = new char[8 * 1024];
                    //边度编写,实现 缓冲字符流的 readLine 一行
                    while ((str = br.readLine()) != null) {
                        sb.append(str);
                    }
                    String result = sb.toString();
                    Log.e(Tag, result);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Android 中进行 JSON 的 POST 和 GET 请求,可以使用 Android 所提供的 HttpUrlConnection 类或者 Volley 框架,以下分别介绍两种方法: 1. 使用 HttpUrlConnection 进行 POST 和 GET 请求: - POST 请求: ```java URL url = new URL("http://example.com/api"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); conn.setDoInput(true); JSONObject jsonParam = new JSONObject(); jsonParam.put("param1", "value1"); jsonParam.put("param2", "value2"); DataOutputStream os = new DataOutputStream(conn.getOutputStream()); os.writeBytes(jsonParam.toString()); os.flush(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Handle response } else { // Error handling } ``` - GET 请求: ```java URL url = new URL("http://example.com/api?param1=value1&param2=value2"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); conn.setRequestProperty("Accept", "application/json"); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Handle response } else { // Error handling } ``` 2. 使用 Volley 进行 POST 和 GET 请求: - POST 请求: ```java String url = "http://example.com/api"; JSONObject jsonParam = new JSONObject(); jsonParam.put("param1", "value1"); jsonParam.put("param2", "value2"); JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonParam, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // Handle response } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Error handling } }); request.setRetryPolicy(new DefaultRetryPolicy( 5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); RequestQueue queue = Volley.newRequestQueue(context); queue.add(request); ``` - GET 请求: ```java String url = "http://example.com/api?param1=value1&param2=value2"; JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // Handle response } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Error handling } }); request.setRetryPolicy(new DefaultRetryPolicy( 5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); RequestQueue queue = Volley.newRequestQueue(context); queue.add(request); ``` 需要注意的是,以上代码仅为示例,具体实现需要根据实际情况进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值