okhttp和volley

OkHttp

Okhttp(第三方框架,必须掌握,需要封装)
okhttp是一个第三方类库,用于android中请求网络。
这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) 。用于替代HttpUrlConnection和Apache HttpClient(android API23 里已移除HttpClient)。

1.同步get请求:开启子线程
2.同步post请求:开启子线程
3.异步get请求:不需要开启子线程
4.异步post请求:不需要开启子线程

Volley

所谓Volley,它是2013年Google I/O上发布的一款网络框架,基于Android平台,能使网络通信更快,更简单,更健全

优点:
(1)默认Android2.3及以上基于HttpURLConnection,2.3以下使用基于HttpClient;
(2)符合Http 缓存语义 的缓存机制(提供了默认的磁盘和内存等缓存);
(3)请求队列的优先级排序;
(4)提供多样的取消机制;
(5)提供简便的图片加载工具(其实图片的加载才是我们最为看重的功能);(6)一个优秀的框架。

缺点:
它只适合数据量小,通信频繁的网络操作,如果是数据量大的,像音频,视频等的传输,还是不要使用Volley的为好

理论千篇一律,但代码万里挑一
来吧枕头们and累嘚死

public class HttpUtils  {
    final static String TAG = "###";
    public static void httpurlconnect_post(String s){
        try {
            URL url = new URL(s);
            HttpURLConnection http = (HttpURLConnection)url.openConnection();
            http.setRequestMethod("POST");
            http.setReadTimeout(200);
            http.setConnectTimeout(200);

            http.setDoInput(true);
            http.setDoOutput(true);

            OutputStream stream = http.getOutputStream();

            stream .write("phone=18765571722&passwd=123321".getBytes());
            stream.flush();

            if(http.getResponseCode() == 200){
                InputStream is = http.getInputStream();
                int len = 0;
                byte[] bytes = new byte[1024];
                StringBuilder sb = new StringBuilder();
                while ((len = is.read(bytes))!=-1){
                    String str = new String(bytes,0,len);
                    sb.append(str);
                }
                Log.i(TAG, "httpurlconnect_post: "+sb.toString());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void OKHttp_Get(String s){
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder().url(s).get().build();
        Call call = client.newCall(request);
        try {
            String string = call.execute().body().string();
            Log.i(TAG, "OKHttp_Get: "+string);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void OKHttp_post(String s){
        FormBody body = new FormBody.Builder()
                .add("phone", "18465571722")
                .add("passwd", "321654")
                .build();
        Request request = new Request.Builder().url(s).post(body).build();
        OkHttpClient client = new OkHttpClient.Builder().build();
        try {
            Response execute = client.newCall(request).execute();
            Log.i(TAG, "OKHttp_post: "+execute.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 异步
     */
    public static void asyncGet(String s){
        Request build = new Request.Builder().url(s).build();
        OkHttpClient client = new OkHttpClient();
        Call call = client.newCall(build);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, "onFailure: 失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i(TAG, "onFailure: 成功");
                Log.i(TAG, "onResponse: "+response.body().string());
            }
        });
    }
    /**
     * 异步post
     */
    public static void asyncPost(String s){
        FormBody body = new FormBody.Builder()
                .add("phone", "18365571722")
                .add("passwd", "321654")
                .build();
        Request request = new Request.Builder().url(s).post(body).build();
        OkHttpClient client = new OkHttpClient.Builder().build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(TAG, "onFailure: 失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i(TAG, "onFailure: 成功");
                Log.i(TAG, "onResponse: "+response.body().string());
            }
        });
    }

    public static void volleyImage(String s,Context context) {
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        ImageRequest imageRequest = new ImageRequest(s,bitmapListener,100,100,Bitmap.Config.RGB_565,errorListener);
        requestQueue.add(imageRequest);
        requestQueue.start();
    }
    static com.android.volley.Response.Listener<Bitmap> bitmapListener = new com.android.volley.Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap response) {
            MainActivity.imageView.setImageBitmap(response);
        }
    };
    public static void volleyGet(String s, Context context){
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        StringRequest request = new StringRequest(StringRequest.Method.GET, s, stringListener, errorListener);

        requestQueue.add(request);
        requestQueue.start();
    }
    public static void VolleyPost(String s,Context context){
        StringRequest request = new StringRequest(StringRequest.Method.POST, s, stringListener, errorListener){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> map = new HashMap<>();
                map.put("phone","13741661031");
                map.put("passwd","135");

                return map;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(request);
        requestQueue.start();
    }
    static com.android.volley.Response.Listener<String> stringListener = new com.android.volley.Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i(TAG, "onResponse: "+response);
        }
    };
    static com.android.volley.Response.ErrorListener errorListener = new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    };
}

INTERESTING!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值