我正在尝试测试我的应用程序,该应用程序向服务器发送REST请求并检索一些fileNames。我正在尝试部署以下两个类:
@ApplicationPath("/")
public class JaxRsActivator extends Application {
}
和
@Path("/files")
@RequestScoped
public class RestEndpointMock {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getFileNames() {
return new MockResponse();
}
private class MockResponse extends Response {
@Override
public Object getEntity() {
return new MockEntity();
}
}
private class MockEntity implements HttpEntity {
@Override
public InputStream getContent() throws IOException, UnsupportedOperationException {
return ByteArrayInputStream(fileNamesAsJson.getBytes(StandardCharsets.UTF_8));
}
}
}
目标是当实际的用例发送一个REST请求时,这个模拟的接口被命中,它返回模拟的文件名列表。
我正在构建请求,如下所示(对于测试调用,禁用SSL证书错误):
public static HttpClient createHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
final SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
}, new SecureRandom());
final SSLSocketFactory sf = new SSLSocketFactory(sslContext);
final Scheme httpsScheme = new Scheme("https", 443, sf);
final SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);
final ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
final HttpClient httpClient = new DefaultHttpClient(cm);
return httpClient;
}
然后最终发送请求为:
private HttpResponse sendPostRequest(){
final HttpClient httpClient = createHttpClient();
final String postUrl = String.format(https://localhost/login);
final HttpPost postRequest = new HttpPost(postUrl);
return httpClient.execute(postRequest)
}
但是在尝试这种方式时我最终得到了ConnectionRefused异常。不确定我是否错误地设置了模拟端点,或者在此过程中是否有其他东西搞砸了。