美文网首页
Android开发之使用Volley

Android开发之使用Volley

作者: 我是谢叔叔 | 来源:发表于2016-12-02 21:33 被阅读0次

    Volley常用用法#

    1. 创建一个RequestQueue。
    2. 创建一个Request(StringRequest, JsonObjectRequest, ImageRequest)。
    3. 将Request加入到RequestQueue中。

    遇到的问题#

    最近公司在做项目的时候,后端提供的接口中是post一个json数据结构的参数过去,返回的数据是json/string的数据。一开始我使用的是JsonObjectRequest的post方法来请求数据,但是数据的返回结构不是json数据格式的时候抛出了异常。最后还是google大法好。使用StringRequest来请求数据,问就迎刃而解了。StringRequest怎么post一个json数据呢?

    • 重写getBody方法
    @Override 
    public byte[] getBody() { 
          JSONObject jsonObject = new JSONObject();
          String body = null; 
          try {
                jsonObject.put("username", "user123");
                jsonObject.put("password", "Pass123");   
                body = jsonObject.toString(); 
          } catch (JSONException e) {
                 // TODO Auto-generated catch block e.printStackTrace(); 
          }
          try {
                  return body.toString().getBytes("utf-8"); 
          } catch (UnsupportedEncodingException e) { 
                // TODO Auto-generated catch block e.printStackTrace(); 
          } 
              return null; 
       }
    
    • 重写getBodyContentType方法

    @Override
    public String getBodyContentType() {
    return "application/json";
    }

    #最后
    重写这两个方法之后就大功告成了。

    相关文章

      网友评论

          本文标题:Android开发之使用Volley

          本文链接:https://www.haomeiwen.com/subject/qbpqmttx.html