OkHttp使用小记——3分钟入门

转载注明出处:-十个雨点

OkHttp是square推出的网络解决方案,俗话说square出品,必属精品,所以我们更有理由相信OkHttp的强大。

OkHttp 处理了很多网络请求的难题:会从很多常用的连接问题中自动恢复。如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。

而且OkHttp使用起来真是非常简单,基本使用只需5步就能搞定,直接看代码。

我使用的是3.4.1版本,可能和以前的版本有些区别。

在build.gradle文件中添加

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

Get

OkHttpClient mOkHttpClient = new OkHttpClient();                                 //1、
Request request = new Request.Builder()
        .url("https://github.com/l465659833")
        .build();                                                                //2、
Call call = mOkHttpClient.newCall(request);                                      //3、
call.enqueue(new Callback()                                                      //4、
{
    @Override
    public void onFailure(Call call, IOException e) {
        Log.e("OkHttp ",e.toString());
    }
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.e("OkHttp ",response.toString());                                     //5、
        Log.e("OkHttp ", response.body().string());
        response.close();
    }
});

Post

String url="http://www.roundsapp.com/post";
String json="{'winCondition':'HIGH_SCORE',"
                + "'name':'Bowling',"
                + "'round':4,"
                + "'lastSaved':1367702411696,"
                + "'dateStarted':1367702378785,"
                + "'players':["
                + "{'name':'" + "Jesse" + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
                + "{'name':'" + "Jake" + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
                + "]}";
OkHttpClient client = new OkHttpClient();                                                                //1、
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);         //1.5、
Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();                                                                                        //2、
Call call = client.newCall(request);                                                                    //3、
call.enqueue(new Callback() {                                                                            //4、
    @Override
    public void onFailure(Call call, IOException e) {

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.e("OkHttp ",response.toString());                                                            //5、
        Log.e("OkHttp ", response.body().string());
        response.close();
    }
});

RequestBody

使用post方法时,需要传入一个RequestBody参数,从名字上就可以看出这是Http协议中的请求体,有以下几种创建方式:

ReuqestBody.create(MediaType contentType, byte[] content)                             //提交字节数组
ReuqestBody.create(MediaType contentType, byte[] content, int offset, int byteCount)  //提交字节数组
ReuqestBody.create(MediaType contentType, File file)                                  //提交文件
ReuqestBody.create(MediaType contentType, String content)                             //提交字符串

其中MediaType 就是我们常用的MIME类型,通过以下方式生成,并制定编码字符集:

MediaType.parse("application/json; charset=utf-8");

同步调用

上面的Get和Post示例中都使用了异步网络请求,如果使用同步方式调用,可以这样:

Call call = client.newCall(request);
Response response=call .execute();
Log.e("OkHttp ", response.body().string());
response.close();

你可能感兴趣的:(OkHttp使用小记——3分钟入门)