首先添加相关库
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.zhy:okhttputils:2.6.2'
默认情况下,将直接使用okhttp默认的配置生成OkhttpClient,如果你有任何配置,记得在Application中调用initClient方法进行设置
OkHttpClient okHttpClient = new OkHttpClient.Builder()
// .addInterceptor(new LoggerInterceptor("TAG"))
.connectTimeout(10000L, TimeUnit.MILLISECONDS)
.readTimeout(10000L, TimeUnit.MILLISECONDS)
//其他配置
.build();
OkHttpUtils.initClient(okHttpClient);
自定义CallBack
import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.Callback;
import okhttp3.Response;
/**
* Created by linqinbin on 2017/3/26.
*/
public abstract class LoginCallback extends Callback<LoginResponse> {
@Override
public LoginResponse parseNetworkResponse(Response response, int id) throws Exception {
String string = response.body().string();
LoginResponse loginResponse = new Gson().fromJson(string, LoginResponse.class);
return loginResponse;
}
}
自定义modal
public class LoginResponse implements Serializable {
public int user_id;
public String sid;
public String access_token;
}
异步请求(baseRequest请求的参数对象modal)
OkHttpUtils
.postString()
.url("http://120.26.106.68:8282/api_v1.php")
.content(new Gson().toJson(baseRequest))
.mediaType(MediaType.parse("application/json; charset=utf-8"))
.build()
.execute(new LoginCallback() {
@Override
public void onError(Call call, Exception e, int id) {
println(e.getMessage());
Toast.makeText(MainActivity.this,"error",Toast.LENGTH_LONG).show();
}
@Override
public void onResponse(LoginResponse response, int id) {
println(response.toString());
Toast.makeText(MainActivity.this,response.user_id+response.access_token+response.sid,Toast.LENGTH_LONG).show();
}
});
同步请求
Response response = OkHttpUtils
.get()//
.url(url)//
.tag(this)//
.build()//
.execute();
//execute方法不传入callback即为同步的请求,返回Response。
网友评论