这是我用到的一个util类
![复制代码](https://common.cnblogs.com/images/copycode.gif)
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 }标签:常用,return,String,示例,url,request,Request,Okhttp,response From: https://www.cnblogs.com/kn-zheng/p/17024784.html