2017年7月8日注:
此文(分割线下面的文字)是我两年前写的。现在已经出了OkHttp3,我也写了最新的用法,DEMO地址:https://github.com/chenglin198751/BaseMyProject 。里面有个HttpUtils.java 文件就是具体的用法。建议大家用最新的OkHttp3 。
=========================分割线==========================
以前用的是原生的httpClient,但是有很多问题,比如重连机制啊,超时处理,等等,都需要自己写,而自己写又写不那么完善。
square开源的OkHttp很多人都在用,我试了下确实很不错,以后就打算用这个。
官网:http://square.github.io/okhttp/
注意,需要它需要okio包支持:https://github.com/square/okio
官方帮助文档:https://github.com/square/okhttp/wiki/Recipes
这里就简单的记录下它的Post用法:
第一种是需要在线程里运行的:
public String postKeyValue(String actionType, String jsonString, String url) throws HttpException, IOException {
String result = null;
FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
addCommonData(formEncodingBuilder);
formEncodingBuilder.add("actionType", actionType);
formEncodingBuilder.add(Value.JSON_STR, jsonString);
RequestBody formBody = formEncodingBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()){
result = response.body().string();
}else {
throw new IOException("Unexpected code " + response);
}
return result;
}
第二种是直接请求成功后给回调的:
public void postKeyValue(String actionType, String jsonString, String url) throws HttpException, IOException {
FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder();
addCommonData(formEncodingBuilder);
formEncodingBuilder.add("actionType", actionType);
formEncodingBuilder.add(Value.JSON_STR, jsonString);
RequestBody formBody = formEncodingBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(final Response response) throws IOException {
if (response.isSuccessful()) {
String result = response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
});
}
===============================
如果你觉得帮到了你,请给作者打赏一口饭吃: