这篇文章将为大家详细讲解有关怎么在spring中远程调用HttpClient和RestTemplate,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。一、HttpClient导入坐标<d
这篇文章将为大家详细讲解有关怎么在spring中远程调用HttpClient和RestTemplate,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
导入坐标
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version></dependency>
//1、使用HttpClient发起Get请求public class DoGET { public static void main(String[] args) throws Exception { // 创建Httpclient对象,相当于打开了浏览器 CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建HttpGet请求,相当于在浏览器输入地址 HttpGet httpGet = new HttpGet("http://www.baidu.com/"); CloseableHttpResponse response = null; try { // 执行请求,相当于敲完地址后按下回车。获取响应 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { // 解析响应,获取数据 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { // 关闭资源 response.close(); } // 关闭浏览器 httpclient.close(); } }} //2、使用HttpClient发起带参数的Get请求public class DoGETParam { public static void main(String[] args) throws Exception { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建URI对象,并且设置请求参数 URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); // HttpGet get = new HttpGet("http://www.baidu.com/s?wd=java"); CloseableHttpResponse response = null; try { // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { // 解析响应数据 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } httpclient.close(); } }} //3、使用HttpClient发起POST请求public class DoPOST { public static void main(String[] args) throws Exception { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建http POST请求 HttpPost httpPost = new HttpPost("http://www.oschina.net/"); // 把自己伪装成浏览器。否则开源中国会拦截访问 httpPost.setHeader("User-Agent", "Mozilla/5.0 (windows NT 10.0; WOW64) AppleWEBKit/537.36 (Khtml, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); CloseableHttpResponse response = null; try { // 执行请求 response = httpclient.execute(httpPost); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { // 解析响应数据 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } // 关闭浏览器 httpclient.close(); } }} //4、使用HttpClient发起带有参数的POST请求public class DoPOSTParam { public static void main(String[] args) throws Exception { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建http POST请求,访问开源中国 HttpPost httpPost = new HttpPost("http://www.oschina.net/search"); // 根据开源中国的请求需要,设置post请求参数 List<NameValuePair> parameters = new ArrayList<NameValuePair>(0); parameters.add(new BasicNameValuePair("scope", "project")); parameters.add(new BasicNameValuePair("q", "java")); parameters.add(new BasicNameValuePair("fromerr", "8bDnUWwC")); // 构造一个fORM表单式的实体 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); // 将请求实体设置到httpPost对象中 httpPost.setEntity(formEntity); CloseableHttpResponse response = null; try { // 执行请求 response = httpclient.execute(httpPost); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { // 解析响应体 String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } // 关闭浏览器 httpclient.close(); } }}
导入坐标
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>
创建RestTemplate对象
@Configuration//加上这个注解作用,可以被Spring扫描public class RestTemplateConfig { @Bean public RestTemplate restTemplate(){ RestTemplate restTemplate = new RestTemplate(); //主要解决中文乱码 restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); return restTemplate; }}
RestTempController
import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; @RestController@RequestMapping("/consumer")public class ConsumerController { // 从Spring的容器中获取restTemplate @Resource private RestTemplate restTemplate; @GetMapping("/{id}") public ResponseEntity<String> findById(@PathVariable Integer id){ //发起远程请求:通过RestTemplate发起get请求 ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:8090/Goods2/1", String.class); System.out.println("entity.getStatusCode():"+entity.getStatusCode()); System.out.println(entity.getBody()); return entity; } @PostMapping public ResponseEntity<String> saveGoods(@RequestBody Goods goods){ //通过RestTemplate发起远程请求 ResponseEntity<String> entity = restTemplate.postForEntity("http://localhost:8090/goods2", goods, String.class); System.out.println("entity.getStatusCode():"+entity.getStatusCode()); System.out.println(entity.getBody()); return entity; } @PutMapping public ResponseEntity<String> updateGoods(@RequestBody Goods goods){ restTemplate.put("http://localhost:8090/goods2",goods); return new ResponseEntity<>("修改成功", httpstatus.OK); } @DeleteMapping("/{id}") public ResponseEntity<String> deleteById(@PathVariable Integer id){ restTemplate.delete("http://localhost:8090/goods2/"+id); return new ResponseEntity<>("删除成功", HttpStatus.OK); }}
只用Maven不用SpringBoot框架时只需要导入依赖到pom文件
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId></dependency>
直接new RestTemplate()对象使用即可
关于怎么在Spring中远程调用HttpClient和RestTemplate就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
--结束END--
本文标题: 怎么在Spring中远程调用HttpClient和RestTemplate
本文链接: https://lsjlt.com/news/249918.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0