如何在Java中捕获HTTP请求并模拟其响应?

如何在Java中捕获HTTP请求并模拟其响应?,java,http,mocking,wiremock,http-mock,Java,Http,Mocking,Wiremock,Http Mock,假设Java应用程序向http://www.google.com/...而且无法配置继承的库(在内部发出此类请求),因此我无法存根或替换此URL 请分享一些最佳实践来创建一个类似模拟的 whenCalling(“http://www.google.com/some/path“”。使用方法(“GET”)。然后使用ExpectResponse(“HELLO”) 因此,在当前JVM进程的上下文中,任何HTTP客户端对该URL发出的请求都将被重定向到mock,并替换为该响应“HELLO” 我试图用Wir

假设Java应用程序向
http://www.google.com/...
而且无法配置继承的库(在内部发出此类请求),因此我无法存根或替换此URL

请分享一些最佳实践来创建一个类似模拟的

whenCalling(“http://www.google.com/some/path“”。使用方法(“GET”)。然后使用ExpectResponse(“HELLO”)

因此,在当前JVM进程的上下文中,任何HTTP客户端对该URL发出的请求都将被重定向到mock,并替换为该响应
“HELLO”

我试图用WireMock、Mockito或Hoverfly找到一个解决方案,但它们似乎做了一些不同的事情。也许我只是没能正确地使用它们

您能否从
main
方法中显示一个简单的设置,如:

  • 创建模拟
  • 启动模拟仿真
  • 通过任意HTTP客户端向URL发出请求(不要与模拟库纠缠在一起)
  • 收到嘲笑的回应
  • 停止模拟模拟
  • 提出与步骤3相同的请求
  • 从URL接收真实响应

  • 以下是如何通过以下方法实现您想要的

    该示例演示了将嵌入式API模拟器配置为Spring的RestTemplate客户端的HTTP代理的两种不同方法。请参阅(问题中的引语)“继承库”的文档,通常基于Java的客户端依赖于所描述的系统属性,或者可能提供一些方法来使用代码配置HTTP代理

    package others;
    
    import static com.apisimulator.embedded.SuchThat.*;
    import static com.apisimulator.embedded.http.HttpApiSimulation.*;
    
    import java.net.InetSocketAddress;
    import java.net.Proxy;
    import java.net.Proxy.Type;
    import java.net.URI;
    
    import org.junit.Assert;
    import org.junit.BeforeClass;
    import org.junit.ClassRule;
    import org.junit.Test;
    import org.springframework.http.ResponseEntity;
    import org.springframework.http.client.SimpleClientHttpRequestFactory;
    import org.springframework.web.client.RestTemplate;
    
    import com.apisimulator.embedded.http.JUnitHttpApiSimulation;
    
    public class EmbeddedSimulatorAsProxyTest
    {
    
       // Configure an API simulation. This starts an instance of
       // Embedded API Simulator on localhost, default port 6090.
       // The instance is automatically stopped when the test ends.
       @ClassRule
       public static final JUnitHttpApiSimulation apiSimulation = JUnitHttpApiSimulation
             .as(httpApiSimulation("my-sim"));
    
       @BeforeClass
       public static void beforeClass()
       {
          // Configure simlets for the API simulation
          // @formatter:off
          apiSimulation.add(simlet("http-proxy")
             .when(httpRequest("CONNECT"))
             .then(httpResponse(200))
          );
    
          apiSimulation.add(simlet("test-google")
             .when(httpRequest()
                   .whereMethod("GET")
                   .whereUriPath(isEqualTo("/some/path"))
                   .whereHeader("Host", contains("google.com"))
              )
             .then(httpResponse()
                   .withStatus(200)
                   .withHeader("Content-Type", "application/text")
                   .withBody("HELLO")
              )
          );
          // @formatter:on
       }
    
       @Test
       public void test_using_system_properties() throws Exception
       {
          try
          {
             // Set these system properties just for this test
             System.setProperty("http.proxyHost", "localhost");
             System.setProperty("http.proxyPort", "6090");
    
             RestTemplate restTemplate = new RestTemplate();
    
             URI uri = new URI("http://www.google.com/some/path");
             ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
    
             Assert.assertEquals(200, response.getStatusCode().value());
             Assert.assertEquals("HELLO", response.getBody());
          }
          finally
          {
             System.clearProperty("http.proxyHost");
             System.clearProperty("http.proxyPort");
          }
       }
    
       @Test
       public void test_using_java_net_proxy() throws Exception
       {
          SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    
          // A way to configure API Simulator as HTTP proxy if the HTTP client supports it
          Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("localhost", 6090));
          requestFactory.setProxy(proxy);
    
          RestTemplate restTemplate = new RestTemplate();
          restTemplate.setRequestFactory(requestFactory);
    
          URI uri = new URI("http://www.google.com/some/path");
          ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
    
          Assert.assertEquals(200, response.getStatusCode().value());
          Assert.assertEquals("HELLO", response.getBody());
       }
    
       @Test
       public void test_direct_call() throws Exception
       {
          RestTemplate restTemplate = new RestTemplate();
    
          URI uri = new URI("http://www.google.com");
          ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
    
          Assert.assertEquals(200, response.getStatusCode().value());
          Assert.assertTrue(response.getBody().startsWith("<!doctype html>"));
       }
    
    }
    
    。。。这指向存储库:

      <repositories>
        <repository>
            <id>apisimulator-github-repo</id>
            <url>https://github.com/apimastery/APISimulator/raw/maven-repository</url>
         </repository>
      </repositories>
    
    
    ApiHub回购协议
    https://github.com/apimastery/APISimulator/raw/maven-repository
    
    如果您无法控制代码,则可能需要在操作系统级别上重写调用太棒了!这可能比我想象的还要好。您能否在答案中添加maven依赖项,这是在项目中使用API模拟器所必需的?在那之后,答案将是完整的,我将接受它。Hi@diziaq——编辑了答案,添加了关于如何将嵌入式API模拟器作为依赖项添加到maven管理的项目的信息。你应该看看真正的主力-独立API模拟器:-)干杯
      <repositories>
        <repository>
            <id>apisimulator-github-repo</id>
            <url>https://github.com/apimastery/APISimulator/raw/maven-repository</url>
         </repository>
      </repositories>