package com.itheima.config; import lombok.Getter; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Getter @Component public class ApplicationValues { @Value("${http_pool.max_total}") private int maxTotal; @Value("${http_pool.default_max_per_route}") private int maxPerRoute; @Value("${http_pool.connect_timeout}") private int connTimeOut; @Value("${http_pool.connection_request_timeout}") private int connReqTimeOut; @Value("${http_pool.socket_timeout}") private int socketTimeout; @Value("${http_pool.validate_after_inactivity}") private int inactivity; }
package com.itheima.config; import com.itheima.controller.UserController; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.stereotype.Component; @Component public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(UserController.class); } }
package com.itheima.config; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @Configuration public class RestTemplateConfig { @Autowired private ApplicationValues appValues; @Bean public RestTemplate restTemplate() { return new RestTemplate(httpRequestFactory()); } @Bean public ClientHttpRequestFactory httpRequestFactory() { return new HttpComponentsClientHttpRequestFactory(httpClient()); } @Bean public HttpClient httpClient() { Registryregistry = RegistryBuilder. create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", SSLConnectionSocketFactory.getSocketFactory()) .build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); connectionManager.setMaxTotal(appValues.getMaxTotal()); connectionManager.setDefaultMaxPerRoute(appValues.getMaxPerRoute()); connectionManager.setValidateAfterInactivity(appValues.getInactivity()); RequestConfig requestConfig = RequestConfig.custom() //服务器返回数据(response)的时间,超过抛出read timeout .setSocketTimeout(appValues.getSocketTimeout()) //连接上服务器(握手成功)的时间,超出抛出connect timeout .setConnectTimeout(appValues.getConnTimeOut()) //从连接池中获取连接的超时时间,超时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool .setConnectionRequestTimeout(appValues.getConnReqTimeOut()) .build(); return HttpClientBuilder.create() .setDefaultRequestConfig(requestConfig) .setConnectionManager(connectionManager) .build(); } }
package com.itheima.mock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; @Component public class RestMock{ @Autowired private RestTemplate restTemplate; public HttpEntity
package com.itheima; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class ControllerApplication extends SpringBootServletInitializer { public static void main(String[] args) { new ControllerApplication().configure(new SpringApplicationBuilder(ControllerApplication.class)).run(args); } }
package com.itheima.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.config.A; import com.itheima.mock.RestMock; import net.minidev.json.JSONObject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.request; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @RunWith(SpringRunner.class) @SpringBootTest public class UserControllerTest { protected MockMvc mockMvc; //集成Web环境,将会从该上下文获取相应的控制器并得到相应的MockMvc; @Autowired protected WebApplicationContext wac; @Autowired private RestMock restMock; @Before() public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); //构造MockMvc对象 DispatcherServlet dispatcherServlet = mockMvc.getDispatcherServlet(); } //单位数据量统计服务 @Test public void goUnitDataStatSvcTest() throws Exception { Mapmap = new HashMap<>(); String content = JSONObject.toJSonString(map); URL url = new URL("http://localhost:8080/v1/v2"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 提交模式 conn.setRequestMethod("POST");// POST GET PUT DELETE conn.setRequestProperty("Authorization", "Basic YWRtaW46YWRtaW4=");//YWRtaW46YWRtaW4="); // 设置访问提交模式,表单提交 conn.setRequestProperty("Content-Type", "application/json"); conn.setConnectTimeout(15000);// 连接超时 单位毫秒 conn.setReadTimeout(15000);// 读取超时 单位毫秒 //读取请求返回值 conn.setDoOutput(true);// 是否输入参数 StringBuffer params = new StringBuffer(); // 表单参数与get形式一样 params.append("f292139625cd4d59fcff42360ce11fc"); byte[] bypes = params.toString().getBytes(); conn.getOutputStream().write(bypes);// 输入参数 byte bytes[]=new byte[1024]; InputStream inStream=conn.getInputStream(); inStream.read(bytes, 0, inStream.available()); System.out.println(new String(bytes, "utf-8")); Map uriMap = new HashMap<>(6); uriMap.put("name", "张耀烽"); uriMap.put("sex", "男"); A a=new A(); a.setName("小明"); a.setAge("12"); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writevalueAsString(a); String s = restMock.sendPost("http://localhost:8080/v1/v2",json); System.out.println(a); // String result = mockMvc.perform(post("http://localhost:8080/v1/v2") // .contentType(MediaType.APPLICATION_JSON_UTF8) // 请求中的媒体类型信息—json数据格式 // .content(content)) // RequestBody信息 // .andDo(print()) // 打印出请求和相应的内容 // .andReturn().getResponse().getContentAsString(); // 返回MvcResult并且转为字符串 // Assert.assertNotNull(result); } @Test public void testGet() throws Exception{ A a=new A(); a.setAge("12"); ObjectMapper mapper = new ObjectMapper(); String url = "http://localhost:8080/v1/v2/"; URL x = new URL("http://localhost:8080/v1/v2"); //访问路径为:http://:/<应用域>/clientWeb/getData String json = mapper.writevalueAsString(a); String result = mockMvc.perform(request(HttpMethod.POST, "http:///v1/v2") .contentType(MediaType.APPLICATION_JSON_UTF8) // 请求中的媒体类型信息—json数据格式 .content(json)) // RequestBody信息 .andDo(print()) // 打印出请求和相应的内容 .andReturn().getResponse().getContentAsString(); // 返回MvcResult并且转为字符串 Assert.assertNotNull(result); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)