首页 > 代码库 > Okhttp常用方法示例
Okhttp常用方法示例
这是我用到的一个util类
1 public class HttpBaseService { 2 3 private OkHttpClient client = new OkHttpClient(); 4 private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); 5 public String sendGetRequest(String url){ 6 Request request = new Request.Builder().url(url).build(); 7 Response response = null; 8 try { 9 response = client.newCall(request).execute(); 10 if (response.isSuccessful()) { 11 return response.body().string(); 12 } 13 } catch (IOException e) { 14 e.printStackTrace(); 15 } 16 return ""; 17 } 18 19 public int sendDelRequest(String url){ 20 Request request = new Request.Builder().url(url).delete().build(); 21 return sendOperateRequest(request); 22 } 23 24 public int sendPostRequest(String url,String json){ 25 // RequestBody formBody = new FormEncodingBuilder() 26 // .add("platform", "android") 27 // .add("name", "bug") 28 // .add("subject", "XXXXXXXXXXXXXXX") 29 // .build(); 30 RequestBody body = RequestBody.create(JSON,json); 31 Request request = new Request.Builder().url(url).post(body).build(); 32 return sendOperateRequest(request); 33 } 34 public int sendPutRequest(String url,String json){ 35 RequestBody body = RequestBody.create(JSON,json); 36 Request request = new Request.Builder().url(url).put(body).build(); 37 return sendOperateRequest(request); 38 } 39 40 private int sendOperateRequest(Request request){ 41 Response response = null; 42 try { 43 response = client.newCall(request).execute(); 44 if (response.isSuccessful()) { 45 return 0; 46 } 47 } catch (IOException e) { 48 e.printStackTrace(); 49 } 50 return -1; 51 } 52 }
Okhttp常用方法示例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。