okhttp的简单使用

来源:互联网 发布:python使用教程 编辑:程序博客网 时间:2024/05/20 05:11

OkHttp是一个很棒HTTP客户端:

  • 支持SPDY,可以合并多个到同一个主机的请求

  • 使用连接池技术减少请求的延迟(如果SPDY是可用的话)

  • 使用GZIP压缩减少传输的数据量

  • 缓存响应避免重复的网络请求

当你的网络出现拥挤的时候,就是OKHttp大显身手的时候,它可以避免常见的网络问题,如果你的服务是部署在不同的IP上面的,如果第一个连接失败,OkHTtp会尝试其他的连接。这对现在IPv4+IPv6中常见的把服务冗余部署在不同的数据中心上也是很有必要的。OkHttp将使用现在TLS特性(SNI ALPN)来初始化新的连接,如果握手失败,将切换到TLS 1.0。

  • 使用OkHttp很容易,同时支持异步阻塞请求和回调.

如果你使用OkHttp ,你不用重写你的代码, okhttp-urlconnection模块实现了 java.net.HttpURLConnection 中的API, okhttp-apache模块实现了HttpClient中的API


在使用的过程中,在此,我们以AS作为开发工具,在build.gradle中添加如下依赖,根据okhttp 的版本:

    compile 'com.squareup.okhttp3:okhttp:3.2.0'

在这里我们简单使用一个单例模式,我们把所有的网络数据请求操作全都放在这里:

public class OKHttpHelper{private static OKHttpHelper instance = null;public static OKhttpHelper getInstance() {        if (instance == null) {            instance = new OKhttpHelper();        }        return instance;    }private OKHttpHelper(){}//一些相关的配置设置public static final MediaType JSON            = MediaType.parse("application/json; charset=utf-8");    private OkHttpClient client = new OkHttpClient.Builder()            .connectTimeout(5, TimeUnit.SECONDS)            .readTimeout(5, TimeUnit.SECONDS)            .build();}//post请求public String post(String url, String json) throws IOException {        RequestBody body = RequestBody.create(JSON, json);        Request request = new Request.Builder()                .url(url)                .post(body)                .build();        Response response = client.newCall(request).execute();        if (response.isSuccessful()) {            return response.body().string();        } else {            return "";        }    }    /**     * 同步Server 关闭房间信息     */    public LiveInfoJson notifyServerLiveStop(String id) {        try {            JSONObject stopLive = new JSONObject();            stopLive.put("uid", id);            stopLive.put("watchCount", 1000);            stopLive.put("admireCount", 0);            stopLive.put("timeSpan", 200);            String json = stopLive.toString();            String res = post(STOP_ROOM, json);            SxbLog.i(TAG, "notifyServer live stop  liveinfo: " + res);            JSONTokener jsonParser = new JSONTokener(res);            JSONObject response = (JSONObject) jsonParser.nextValue();            int code = response.getInt("errorCode");            if (code == 0) {                JSONObject data = response.getJSONObject("data");                JSONObject record = data.getJSONObject("record");                String recordS = record.toString();                Gson gson = new GsonBuilder().create();                LiveInfoJson result = gson.fromJson(recordS, LiveInfoJson.class);                return result;            }        } catch (JSONException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return null;    }
0 0
原创粉丝点击