对这玩意并不熟,网上有很多大神封装好的,但是懒得看里面的封装逻辑,索性自己简单做个封装,方便使用,出现bug也好查找:
get请求:
/** * get请求 * @param url * @param callback */ public static void requestByGet(String url,Callback callback){ String baseUrl = ""; OkHttpClient mOkHttpClient = new OkHttpClient(); //创建一个Request final Request request = new Request.Builder() .url(baseUrl + url) .build(); mOkHttpClient.newCall(request).enqueue(callback); }
post请求:
/** * post请求 * @param url * @param map * @param callback * @throws IOException */ public static void requestByPost(String url ,HashMap<String,Object> map,Callback callback) { String baseUrl = ""; FormEncodingBuilder formEncodingBuilder = new FormEncodingBuilder(); for(String key:map.keySet()){ formEncodingBuilder.add(key, map.get(key) + ""); } RequestBody body = formEncodingBuilder.build(); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(baseUrl+url) .post(body) .build(); client.newCall(request).enqueue(callback); }
使用方法:
String url=""; HashMap<String,Object> map=new HashMap<>(); map.put("userid",userId);//自己的接口参数 HttpUtils.requestByPost(url, map, new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { String data = response.body().string(); parseData(data);//解析json串,方法根据自己的写,这儿只是演示 } });