【测试test】

【测试test】,第1张

【测试test】

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() {
        Registry registry = 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> generatePostJson(Map jsonMap) {

        //如果需要其它的请求信息、都可以在这里追加
        HttpHeaders httpHeaders = new HttpHeaders();

        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");

        httpHeaders.setContentType(type);

        HttpEntity> httpEntity = new HttpEntity<>(jsonMap, httpHeaders);

        return httpEntity;
    }


    
    public String generateRequestParameters(String protocol, String uri, Map params) {
        StringBuilder sb = new StringBuilder(protocol).append("://").append(uri);
        if (params != null) {
            sb.append("?");
            for (Map.Entry map : params.entrySet()) {
                sb.append(map.getKey())
                        .append("=")
                        .append(map.getValue())
                        .append("&");
            }
            uri = sb.substring(0, sb.length() - 1);
            return uri;
        }
        return sb.toString();
    }

    
    public String sendGet() {
        Map uriMap = new HashMap<>(6);
        uriMap.put("name", "张耀烽");
        uriMap.put("sex", "男");

        ResponseEntity responseEntity = restTemplate.getForEntity
                (
                        generateRequestParameters("http", "127.0.0.1:80", uriMap),
                        String.class
                );
        return (String) responseEntity.getBody();
    }

    
    public String sendPost() {
        String uri = "http://127.0.0.1:80";

        Map jsonMap = new HashMap<>(6);
        jsonMap.put("name", "张耀烽");
        jsonMap.put("sex", "男");

        ResponseEntity apiResponse = restTemplate.postForEntity
                (
                        uri,
                        generatePostJson(jsonMap),
                        String.class
                );
        return apiResponse.getBody();
    }


    public String sendPost(String url,Object obj) {
        Map stringStringMap = null;
       try {
           stringStringMap = object2Map(obj);
       }catch (Exception e){
           e.printStackTrace();
       }
        ResponseEntity apiResponse = restTemplate.postForEntity
                (
                        url,
                        generatePostJson(stringStringMap),
                        String.class
                );
        return apiResponse.getBody();
    }


    private Map object2Map(Object obj) throws Exception{
        if (obj == null) {
            return null;
        }
        Map map = new HashMap();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj).toString());
        }

        return map;
    }

}

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 {
        Map map = 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);





    }


}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5712613.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存