当前位置: 移动技术网 > IT编程>移动开发>Android > 安卓GET与POST网络请求的三种方式

安卓GET与POST网络请求的三种方式

2019年07月30日  | 移动技术网IT编程  | 我要评论

安平丝网,万年屋,如果可以不爱你

我们的应用常常要联网取得网络上的数据,然后进行解析,必须要先取到数据之后才能进行下一步的业务。

故网络请求是常用的操作,下面我介绍常用的三种方式,

  • 第一是比较原始的方法,使用httpurlconnection,
  • 第二是volley框架,
  • 第三是xutils3框架。

1.httpurlconnection方法

这是基于网络通信http协议的网络请求,其它两种框架也是基于http协议的。http协议是一款基于短连接的协议,每次交互完毕后连接断开,而http请求又分为get和post两种方式,get请求比较简单,只需要在网址后面用?拼接请求的资源路径,如百度图片输入动漫关键字的地址

http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%e5%8a%a8%e6%bc%ab,

可以看到index?后面跟了很多&连接的项目,这个&就是代表了一个个搜索的条件,而最后一个word=%e5%8a%a8%e6%bc%ab又是什么意思呢

就是输入的两个字”动漫”,这就是utf-8编码后的字节,中文一个字符会编成三个字节,这是用16进制表示了一个字节。

从中也可以看到get请求的一个限制,那就是不能传递中文,也不适合大数据量的数据提交。

而post则就没这个限制,且安全性也比get请求高,总结就是简单的网络请求用get,比较复杂的要与服务器与交互的就用post请求。

接下来就是发送get请求和post请求了。

get请求

  //1. url
    url url = new url("http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%e5%8a%a8%e6%bc%ab");
    //2. httpurlconnection
    httpurlconnection conn=(httpurlconnection)url.openconnection();
    //3. set(get)
    conn.setrequestmethod("get");
    //4. getinputstream
    inputstream is = conn.getinputstream();
    //5. 解析is,获取responsetext,这里用缓冲字符流
    bufferedreader reader = new bufferedreader(new inputstreamreader(is));
    stringbuilder sb = new stringbuilder();
    string line = null;
    while((line=reader.readline()) != null){
      sb.append(line);
    }
    //获取响应文本
    string responsetext = sb.tostring();

post请求

//1. url
    url url = new url("http://image.baidu.com/search/index");
    //2. httpurlconnection
    httpurlconnection conn = (httpurlconnection)url.openconnection();
    //3. post
    conn.setrequestmethod("post");
    //4. content-type,这里是固定写法,发送内容的类型
    conn.setrequestproperty("content-type", "application/x-www-form-urlencoded");
    //5. output,这里要记得开启输出流,将自己要添加的参数用这个输出流写进去,传给服务端,这是socket的基本结构
    conn.setdooutput(true);
    outputstream os = conn.getoutputstream();
    string param = "tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%e5%8a%a8%e6%bc%ab";
    //一定要记得将自己的参数转换为字节,编码格式是utf-8
    os.write(param.getbytes("utf-8"));
    os.flush();
    //6. is
    inputstream is = conn.getinputstream();
    //7. 解析is,获取responsetext
    bufferedreader reader = new bufferedreader(new inputstreamreader(is));
    stringbuilder sb = new stringbuilder();
    string line = null;
    while((line=reader.readline()) != null){
      sb.append(line);
    }
    //获取响应文本
    string responsetext = sb.tostring();

2.volley框架

get请求

  //1. 创建requestqueue,这是一个请求队列,相当于消息机制处理
  private requestqueue  mqueue = volley.newrequestqueue(this);
    //2. stringrequest
    string url = "http://www.baidu.com";
    stringrequest req = new stringrequest(url, 
        new listener<string>() {
          //请求成功后回调 在主线程中执行
          public void onresponse(string responsetext) {
            //解析json 封装结果数据
            gson gson = new gson();
            //这里用的gson解析json字符串      
            user result=gson.fromjson(responsetext,requestresult.class);
                      }
        }, new errorlistener() {
          //请求出错时 执行回调 在主线程中执行
          public void onerrorresponse(volleyerror error) {
            error.printstacktrace();
          }
        });
  //把req 添加到 请求队列中,一定要记得这一步,不然就相当于没有发送请求
    mqueue.add(req);

post请求

private requestqueue mqueue; 
//post请求要用commonrequest请求实现
  string url="www.baidu.com";
  commonrequest request = new commonrequest(request.method.post,url,new response.listener<string>() {
      public void onresponse(string response) {
        try {
        //这里是请求成功后调用的接口,用json工具解析数据
          jsonobject obj = new jsonobject(response);
        } catch (jsonexception e) {
          e.printstacktrace();
        }
      }
    },new response.errorlistener() {
      public void onerrorresponse(volleyerror error) {
      }
    }){
      //如果用post请求,要添加参数,一定要重写这个方法来添加参数
      @override
      protected map<string, string> getparams() throws authfailureerror {
        map<string, string> resultmap = new hashmap<string, string>();
        //这里的添加的具体参数   resultmap.put("username",user.getname());
        resultmap.put("userage",user.getage());
        resultmap.put("usergender",user.getgender());
resultmap.put("userschool",user.getschool());
        return resultmap;
      }
    };
    mqueue.add(request);
  }

3.xutils3框架

get请求

//第一步,新建一个请求参数对象
requestparams params=new requestparams("www.baidu.com?inm=2");
//直接调用x.http().get()方法,这里注意x是要用全局myapplication中初始化后才可以使用,初始化方法为x.ext.init(this)
    x.http().get(params, new callback.commoncallback<string>() {
      @override
      public void oncancelled(cancelledexception arg0) {
      }
      @override
      public void onerror(throwable arg0, boolean arg1) {
        log.i("hap.zhu", "http_on_error,请求网络数据失败");
      }
      @override
      public void onfinished() {
      }
      @override
      public void onsuccess(string result) {
        log.i("hap.zhu", "请求数据结果为:"+result);
        gson gson=new gson();
        result result=gson.fromjson(result,result.class);
        log.i("hap.zhu", "加载结果为:"+result.tostring());
    }
    });

post请求

//方法同get,就是这么简单,网络请求成功会回调监听器里的success接口,直接处理数据结果就行
  requestparams params=new requestparams("www.baidu.com");
    params.addbodyparameter("email", username);
    params.addbodyparameter("password", password);
    x.http().post(params, new commoncallback<string>() {
      @override
      public void oncancelled(cancelledexception arg0) {
      }
      @override
      public void onerror(throwable arg0, boolean arg1) {
        //网络错误也会提示错误
        callback.error(arg0.tostring());
      }
      @override
      public void onfinished() {
      }
      @override
      public void onsuccess(string result) {
        gson gson=new gson();
      loginresult loginresult=gson.fromjson(result, loginresult.class);

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网