OkHttp网络请求

jar包

https://yunpan.cn/cRcDaaJbfJgdd  访问密码 ca91

 

get请求

//创建okHttpClient对象
        OkHttpClient okClient = new OkHttpClient();
        //创建一个Request
        final Request request = new Request.Builder()
        .url("http://www.quwenlieqi.com/app/v2/api.php?m=102")
        .build();
        //new call
        Call call = okClient.newCall(request); 
        //请求加入调度
        call.enqueue(new Callback()
                {
                    @Override
                    public void onFailure(Request request, IOException e)
                    {
                        System.out.println("请求失败");
                    }

                    @Override
                    public void onResponse(final Response response) throws IOException
                    {
                        System.out.println("请求成功");
                            String htmlStr =  response.body().string();
                            System.out.println(htmlStr);
                

                 //返回二进制字节数组
                 //byte[] bytes = response.body().bytes();

                 //返回流inputStream
                 //InputStream is = response.body().byteStream();


                    }
                });          
    }

 post请求

// 创建okHttpClient对象
        OkHttpClient okClient = new OkHttpClient();
        FormEncodingBuilder builder = new FormEncodingBuilder();   
//        builder.add("cid","27");
//        builder.add("num","20");

        Request request = new Request.Builder()
                           .url(url)
                        .post(builder.build())
                        .build();
// new call
        Call call = okClient.newCall(request);
        // 请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                System.out.println("请求失败");
            }

            @Override
            public void onResponse(final Response response) throws IOException {
                System.out.println("请求成功");
                //返回字符串
                String htmlStr = response.body().string();
                System.out.println(htmlStr);
                
                //返回二进制字节数组
                //byte[] bytes = response.body().bytes();
                
                //返回流inputStream
                //InputStream is = response.body().byteStream();
            }
        });

 

posted on 2016-06-11 10:37  glj521  阅读(571)  评论(0编辑  收藏  举报