【java】get、post请求的远程调用
POST的调用
public String sendPostRequest() { //请求路径 String inputHost = "http://172.0.0.1:8080/user/getUser"; //请求报文 String inputMessage = "{\"name\":\"张三\",\"age\":\"22\"}"; RestTemplate client = new RestTemplate(); //新建Http头,add方法可以添加参数 HttpHeaders headers = new HttpHeaders(); //设置请求发送方式 HttpMethod method = HttpMethod.POST; //以表单的方式提交 headers.setContentType(MediaType.APPLICATION_JSON); List<MediaType> list = new ArrayList<>(); list.add(MediaType.APPLICATION_JSON_UTF8); headers.setAccept(list); //token修改下 headers.set("Authorization", "token"); //将请求头部和参数合成一个请求 HttpEntity<String> requestEntity = new HttpEntity<>(inputMessage, headers); //执行HTTP请求,将返回的结构使用String 类格式化(可设置为对应返回值格式的类) ResponseEntity<String> response = client.exchange(inputHost, method, requestEntity, String.class); //返回报文 String outputMessage = response.getBody(); return outputMessage; }
GET的调用(未测试)
public String sendGetRequest(String url, Object message) { //请求路径 String inputHost = "http://172.0.0.1:8080/user/getUser"; //请求报文 String inputMessage = "{\"name\":\"张三\",\"age\":\"22\"}"; RestTemplate client = new RestTemplate(); HttpMethod method = HttpMethod.GET; //新建Http头,add方法可以添加参数 HttpHeaders headers = new HttpHeaders(); // 以表单的方式提交 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); //将请求头部和参数合成一个请求 HttpEntity<String> requestEntity = new HttpEntity<>(inputMessage, headers); //执行HTTP请求,将返回的结构使用String 类格式化 ResponseEntity<String> response = client.exchange(inputHost, method, requestEntity, String.class); //返回报文 String outputMessage = response.getBody(); return outputMessage; }
持续更新!!!