向别的后端发起http请求,需要用到http请求,记一下。
http请求
- 下面,包含了get和post,就不分开说了。com.alibaba.fastjson.JSONObject这个没有的话,去maven仓库搜一下,加入pom.xml里。
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
@Service
public class PostData {
public void postArray() {
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8888/";
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("name", "刘");
map.add("name", "流");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, httpHeaders);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
System.out.println(response.getBody());
}
public void post() {
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8888/";
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "无数组");
HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), httpHeaders);
ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.POST, request, JSONObject.class);
System.out.println(response.getBody());
}
public void get() {
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8888/he";
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(httpHeaders);
ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.GET, request, JSONObject.class);
System.out.println(response.getBody());
}
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.Dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class UserController {
UserDao userDao;
@Autowired
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@RequestMapping(method = RequestMethod.POST, value = "/")
@ResponseBody
public JSONObject test(@RequestBody JSONObject map){
System.out.println(map.toString());
JSONObject test = new JSONObject();
test.put("name", "刘");
return test;
}
@RequestMapping(method = RequestMethod.GET, value = "/he")
public JSONObject test1(){
JSONObject test = new JSONObject();
test.put("name", "刘");
return test;
}
}