OkHttp的使用(1)

OkHttp的使用 (1)

本例子使用的是OkHttp官方提供的sample
git下载地址:
https://github.com/square/okhttp

get 数据

如何使用get方法从服务器得到数据

@Test
public void testGetData(){
    //1. 初始化OkHttpClient
    OkHttpClient client = new OkHttpClient();

    //2. 创建一个get请求,注意默认就是get请求
    Request request = new Request.Builder()
            .url("http://www.baidu.com")
            .build();

    //3. 向url发送请求, 此处使用带资源的try语句关闭response,不需要自己手动调用close方法
    try (Response response = client.newCall(request).execute()){
        //4. 打印服务器返回的数据
        System.out.println(response.body().string());
    }catch (IOException e){
        e.printStackTrace();
    }

}

post数据

如何使用post方法向服务器发送数据

@Test
public void testPostData(){
    OkHttpClient client = new OkHttpClient();

    //以post发送数据时候,需要创建一个RequestBody
    MediaType mediaType=MediaType.parse("text/plain;charset=utf-8");

    //传入两个数据,一个数据类型,一个数据的字符串
    RequestBody body=RequestBody.create(mediaType,"postData");
    Request request=new Request.Builder()
            .url("http://www.baidu.com")
            .post(body)
            .build();

    try (Response response = client.newCall(request).execute()){
        System.out.println(response.body().string());
    }catch (IOException e){
        e.printStackTrace();
    }

}

得到服务器header

类似http协议的header

@Test
public void testGetHeader() {
    OkHttpClient client = new OkHttpClient();
    //Accept:接受的数据的类型
    Request request = new Request.Builder()
            .url("https://api.github.com/repos/square/okhttp/issues")
            .header("User-Agent", "OkHttp Headers.java")
            .addHeader("Accept", "application/json; q=0.5")
            .addHeader("Accept", "application/vnd.github.v3+json")
            .build();

    try (Response response = client.newCall(request).execute()) {
        if(!response.isSuccessful())
            throw new IOException(response.message());
        //使用的服务器的信息
        System.out.println("Server: " + response.header("Server"));
        //报文发送日期
        System.out.println("Date: " + response.header("Date"));
        System.out.println("Vary: " + response.headers("Vary"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

异步发送get请求

@Test
public void testAsynchronousGet() throws InterruptedException {
    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url("http://www.baidu.com")
            .build();

    //避免异步时候未返回数据,单元测试就提前结束
    final CountDownLatch latch=new CountDownLatch(1);

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
            latch.countDown();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try (ResponseBody responseBody=response.body()){
                if(!response.isSuccessful())
                    throw new IOException("Unexpected code:" + response);
                Headers headers = response.headers();
                for(int i=0,size=headers.size();i<size;i++){
                    System.out.println(headers.name(i)+":"+headers.value(i));
                }
                System.out.println(responseBody.string());
            }
            latch.countDown();
        }
    });

    latch.await();
}

登录认证

访问某些网站需要认证,此时可以通过OKHttpClient设置认证信息
比如本demo所需访问的界面
登录认证

@Test
public void testAuthenticate() throws IOException {

    OkHttpClient client=new OkHttpClient.Builder()
            .authenticator(new Authenticator() {
                @Override
                public Request authenticate(Route route, Response response) throws IOException {
                    //需要发送两次http协议,第一次请求界面,第二次发送认证信息
                    System.out.println("Authenticating for response: " + response);
                    System.out.println("Challenges: " + response.challenges());
                    //刚开始应该返回401, 未认证
                    System.out.println("code:" + response.code());
                    //设置证书的用户名与密码
                    String credential = Credentials.basic("jesse", "password1");
                    return response.request().newBuilder()
                            .header("Authorization", credential)
                            .build();
                }
            })
            .build();
    Request request = new Request.Builder()
            .url("http://publicobject.com/secrets/hellosecret.txt")
            .build();

    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        System.out.println(response.body().string());
    }

}

版权声明:本文为haizeihdj原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。