在做后端的时候,我们难免会去请求其他应用获取到我们需要的数据。在Spring框架中一般使用HttpClient发送请求的方式,这种方式新手用起来相对麻烦。在SpringBoot中封装了RestTemplate,这种方式简单易学。本篇博客将用作者工作中的实例介绍这两种方式的用法,希望对大家有帮助。作者能力有限,有错请大牛们指教。不喜勿喷。
1.发送GET请求
@GetMapping("/doget")
public String doget() {
// 创建一个可关闭的http客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建get请求
HttpGet request = new HttpGet("http://localhost:8080/gets");
HttpResponse response = null;
try {
//执行请求
response = httpClient.execute(request);
//得到并返回数据
return EntityUtils.toString(response.getEntity(), "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
2.发送POST请求
@GetMapping("/dopost")
public String dopost(String pp) throws IOException {
// 创建一个可关闭的http客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建post请求
HttpPost post = new HttpPost("http://localhost:8080/posts");
/**
* 添加表单数据
*/
// List valuePairs = new ArrayList<>();
// valuePairs.add(new BasicNameValuePair("po", pp));
// HttpEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);
// post.setEntity(entity);
/**
* 添加json数据
*/
JSONObject object=new JSONObject();
object.put("po",pp);
post.addHeader("Content-type", "application/json;charset-utf-8");
post.setEntity(new StringEntity(String.valueOf(object), Charset.forName("UTF-8")));
// 执行请求
HttpResponse response = httpClient.execute(post);
//得到并返回数据
return EntityUtils.toString(response.getEntity());
}
准备工作:为了方便我们会先配置一个bean
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@Configuration
public class HuskyApplication {
public static void main(String[] args) {
SpringApplication.run(HuskyApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
1.发送GET请求
@RestController
public class RequestController {
@Autowired
private RestTemplate template;
@GetMapping("/doget")
public String doget() {
return template.getForObject("http://localhost:8080/gets", String.class);
}
}
2.发送POST请求
2.1发送表单数据
@RestController
public class RequestController {
@Autowired
private RestTemplate template;
@GetMapping("/dopost")
public String dopost() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("mchId", mchId);
map.add("appId", appId);
map.add("productId", productId);
map.add("mchOrderNo", mchOrderNo);
map.add("currency", currency);
map.add("amount", amount);
map.add("returnUrl", returnUrl);
map.add("notifyUrl", notifyUrl);
map.add("subject", subject);
map.add("body", body);
map.add("sign", sign);
HttpEntity<MultiValueMap> entity = new HttpEntity<>(map, headers);
ResponseEntity response = template.exchange("https://127.0.0.1:8080/api/pay/create_order", HttpMethod.POST, entity, String.class);
return String.valueOf(response);
}
}
2.2发送json数据
@RestController
public class RequestController {
@Autowired
private RestTemplate template;
@GetMapping("/dopost")
public String dopost() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject params = new JSONObject();
params.put("tradeDate", record.getTradeDate());
params.put("tradeTime", record.getTradeTime());
params.put("money", record.getMoney());
params.put("tradeType", record.getTradeType());
params.put("remark", record.getRemark());
params.put("identity", record.getIdentity());
params.put("bank", record.getBank());
params.put("bankaccount", record.getBankAccount());// 招行bankaccount 注意a为小写
log.info("数据:"+params);
HttpEntity<String> requestEntity = new HttpEntity<>(params.toJSONString(), headers);
ResponseEntity<String> response = null;
log.info("开始请求!");
try {
response = restTemplate.exchange("http://127.0.0.1:8081/alipayNewTransfer/bank", HttpMethod.POST,
requestEntity, String.class);
log.info("结果:"+response);
} catch (Exception e) {
e.printStackTrace();
}
if (response != null && response.getBody().contains("success")) {
return true;
}
}
}