對這玩意並不熟,網上有不少大神封裝好的,可是懶得看裏面的封裝邏輯,索性本身簡單作個封裝,方便使用,出現bug也好查找:json
get請求:ide
/** * 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
/** * 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); }
使用方法:ui
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串,方法根據本身的寫,這兒只是演示 } });