请求方式
- POST
- GET
POST
单个新增
例如后端接口接收参数为 User user
使用OkHttpClient发送post请求
//封装body信息
JsonObject jsonObject = new JsonObject();
jsonObject.put("userName","张三");
jsonObject.put("city","北京");
String url = "请求接口url"
OkHttpClient okHttpClient = new OkHttpClient();
MediaType json = MediaType.parse("application/json;charset=utf-8);
RequestBody body = RequestBody.create(json,JSON.toJsonString(jsonObject));
Request request = new Request.Builder().url(url).addHeader("Authorization","bearer aga0PU8AVdsas1f9KJfnb").post(body).build();
try{Response response = okHttpClient.newCall(request).execute();if(response.isSucessful() && response.body() != null){System.out.println(response.body.string());}
} catch (Exception e) {e.printStackTrace();
}
GET
使用OkHttpClient发送GET请求,如查询列表
服务端接口http://12.131.23.1/user/list
参数(UserReqDto userReqDto)
String url = "http://12.131.23.1/user/list?userName=张三"OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).addHeader("Authorization","bearer aga0PU8AVdsas1f9KJfnb").get().build();
try{Response response = okHttpClient.newCall(request).execute();if(response.isSucessful() && response.body() != null){System.out.println(response.body.string());}
} catch (Exception e) {e.printStackTrace();
}