SpringBoot 用RestTemplate http测试

本文探讨了在使用SpringBoot的RestTemplate进行http测试时遇到的问题,指出测试类未启动主程序导致的错误。尽管可以通过不指定http://localhost:39900来使测试成功,但每次的端口号都不固定,不遵循配置。虽然不影响开发,但该问题揭示了测试过程中主函数启动与端口加载的不一致性。

spring-boot有关spring-boot测试的一些问题,

这测试的时候主程序没有启动报错。错误如下

==org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:39900/migrate/test": Connect to localhost:39900  [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect; nested exception is org.apache.http.conn.HttpHostConnectException: Connect to localhost:39900 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect

    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:666)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)==

这是因为测试的类写了url 的问题
具体的测试方法如下

package api;

import com.hera.WebApplication;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = WebApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableAutoConfiguration
public class Test {
    @Autowired
    public TestRestTemplate restTemplate;
    @org.junit.Test
    public void home(){

        String url="http://localhost:39900/migrate/test";
      Map map=restTemplate.getForObject(url,Map.class);

        System.out.println(map.get("red"));
    }
}

主函数如下

@ComponentScan(basePackages={"com.hera"})
@SpringBootApplication
@EnableJpaRepositories(repositoryFactoryBeanClass = ExtJpaRepositoryFactoryBean.class)
public class WebApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class, args);
    }
}

这样可以认为是服务没有启动的原因,确实,当服务启动的时候,这个错误就会没有,这时候可以得出一个结论,就是Test的时候主函数是没有启动。需要启动主函数参能测试,
但是有个问题就是
当测试时url不要http://localhost:39900没有起动主函数一样能成功

[INFO][2018-04-29T22:40:02.455+0800][BusinessHandlerInterceptor.java:28] 【LOG HANDLER】 url=http://localhost:63857/migrate/test, traceId=null
..............................
[INFO][2018-04-29T22:40:02.976+0800][BusinessHandlerInterceptor.java:48] 请求参数==> url: http://localhost:63857/migrate/test, spend:0.521秒, contentType: null, params: null, body_params: {}
green

但是端口号不是配置中的那个,还有就是每次端口号都会不一样,真的很奇怪;根本不按照配置来的,我觉得就是它没有都配置,但是默认端口不是8080吗,现在是每次都变,只是随机的一个端口号,从这一面又能看出,其实测试不用单独启动主函数的,测试类会启动,访问不了是因为,端口号不对,但是至于怎么解决目前没有想到. 但是也不影响开发,因为我认为服务端都没启动,客户端怎么能访问呢。至于测试会加载springbootApplication但是端口不一样,没有执行加载端口类的结果。

………………………………………

………………………….

### SpringBoot 中使用 RestTemplate 发送 GET 请求示例 在 SpringBoot 中,`RestTemplate` 是一个用于执行 HTTP 请求的同步客户端。以下是一个完整的示例,展示如何配置和使用 `RestTemplate` 发送 GET 请求[^2]。 #### 1. 配置 RestTemplate 首先需要创建一个配置类来初始化 `RestTemplate` 实例。可以通过注入 `ClientHttpRequestFactory` 来设置连接超时和读取超时时间。 ```java @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) { return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(15000); // 设置连接超时时间为 15 秒 factory.setReadTimeout(5000); // 设置读取超时时间为 5 秒 return factory; } } ``` #### 2. 使用 RestTemplate 发送 GET 请求 接下来可以使用 `RestTemplate` 的方法发送 GET 请求。以下是一个测试用例,展示如何通过 URL 获取数据并将其封装为字符串或对象。 ```java import org.springframework.web.client.RestTemplate; public class RestTemplateExample { public static void main(String[] args) { // 初始化 RestTemplate RestTemplate restTemplate = new RestTemplate(); // 示例 1:发送 GET 请求并接收 String 类型响应 String url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=ACCESS_TOKEN"; String responseString = restTemplate.getForObject(url, String.class); System.out.println("Response as String: " + responseString); // 示例 2:发送 GET 请求并接收自定义对象类型响应 String userUrl = "https://jsonplaceholder.typicode.com/users/1"; User user = restTemplate.getForObject(userUrl, User.class); System.out.println("User Name: " + user.getName()); } } // 自定义对象类 class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` 上述代码展示了两种方式: - 第一种是将返回结果直接解析为字符串[^3]。 - 第二种是将返回结果映射到自定义的 Java 对象中。 #### 3. 处理异常 为了更好地处理网络请求中的异常情况,可以为 `RestTemplate` 设置自定义的错误处理器。 ```java @Configuration public class RestClientConfig { @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new CustomErrorHandler()); return restTemplate; } } // 自定义错误处理器 class CustomErrorHandler implements ResponseErrorHandler { @Override public boolean hasError(ClientHttpResponse response) throws IOException { return response.getStatusCode().is4xxClientError() || response.getStatusCode().is5xxServerError(); } @Override public void handleError(ClientHttpResponse response) throws IOException { throw new HttpClientErrorException(response.getStatusCode(), "Custom error occurred"); } } ``` ### 注意事项 - 在实际项目中,建议将 `RestTemplate` 配置为 Spring Bean 并通过依赖注入使用。 - 如果需要支持异步调用,可以考虑使用 `WebClient` 替代 `RestTemplate`[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值