OkHttp简单用法:导入需要的jar包,定义一个类,写个方法供调用
Private String url;
public void selectAnswerById() {
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("userid", "151")//id
.add("key", "123456")//
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(callback);
}
//请求后的回调方法
private Callback callback = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("OkHttp", "连接失败!");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("OkHttp", response.body().string());
//Gson解析,jsonString返回的json字符串
// String jsonString = response.body().string();
//Gson gson = new Gson();
//gson.fromJson(jsonString ,class);
}
};
单例模式:
public class OkHttpApi {
private static OkHttpApi instance = null;
private OkHttpApi() {
}//默认的构造函数
//单例模式
public static OkHttpApi getInstance() {
if (instance == null) {
synchronized (OkHttpApi.class) {
if (instance == null) {
instance = new OkHttpApi();
}
}
}
return instance;
}
}