下面列出了怎么用org.apache.http.message.BasicHttpEntityEnclosingRequest的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testSimpleSigner() throws Exception {
HttpEntityEnclosingRequest request =
new BasicHttpEntityEnclosingRequest("GET", "/query?a=b");
request.setEntity(new StringEntity("I'm an entity"));
request.addHeader("foo", "bar");
request.addHeader("content-length", "0");
HttpCoreContext context = new HttpCoreContext();
context.setTargetHost(HttpHost.create("localhost"));
createInterceptor().process(request, context);
assertEquals("bar", request.getFirstHeader("foo").getValue());
assertEquals("wuzzle", request.getFirstHeader("Signature").getValue());
assertNull(request.getFirstHeader("content-length"));
}
@Test
public void testEncodedUriSigner() throws Exception {
HttpEntityEnclosingRequest request =
new BasicHttpEntityEnclosingRequest("GET", "/foo-2017-02-25%2Cfoo-2017-02-26/_search?a=b");
request.setEntity(new StringEntity("I'm an entity"));
request.addHeader("foo", "bar");
request.addHeader("content-length", "0");
HttpCoreContext context = new HttpCoreContext();
context.setTargetHost(HttpHost.create("localhost"));
createInterceptor().process(request, context);
assertEquals("bar", request.getFirstHeader("foo").getValue());
assertEquals("wuzzle", request.getFirstHeader("Signature").getValue());
assertNull(request.getFirstHeader("content-length"));
assertEquals("/foo-2017-02-25%2Cfoo-2017-02-26/_search", request.getFirstHeader("resourcePath").getValue());
}
public static String[] getHostNameAndPort(String hostName, int port, SessionId session) {
String[] hostAndPort = new String[2];
String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: \n";
try {
HttpHost host = new HttpHost(hostName, port);
CloseableHttpClient client = HttpClients.createSystem();
URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session);
BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
HttpResponse response = client.execute(host, r);
String url = extractUrlFromResponse(response);
if (url != null) {
URL myURL = new URL(url);
if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
hostAndPort[0] = myURL.getHost();
hostAndPort[1] = Integer.toString(myURL.getPort());
}
}
} catch (Exception e) {
Logger.getLogger(GridInfoExtractor.class.getName()).log(Level.SEVERE, null, errorMsg + e);
}
return hostAndPort;
}
public static GridInfo getHostNameAndPort(String hubHost, int hubPort, SessionId session) {
GridInfo retVal = null;
try {
HttpHost host = new HttpHost(hubHost, hubPort);
DefaultHttpClient client = new DefaultHttpClient();
URL sessionURL = new URL("http://" + hubHost + ":" + hubPort + "/grid/api/testsession?session=" + session);
BasicHttpEntityEnclosingRequest basicHttpEntityEnclosingRequest = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
HttpResponse response = client.execute(host, basicHttpEntityEnclosingRequest);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
JSONObject object = extractObject(response);
retVal = new GridInfo(object);
} else {
System.out.println("Problem connecting to Grid Server");
}
} catch (JSONException | IOException e) {
throw new RuntimeException("Failed to acquire remote webdriver node and port info", e);
}
return retVal;
}
public HttpRequest newHttpRequest(final String method, final String uri) throws MethodNotSupportedException {
if (isOneOf(BASIC, method)) {
return new BasicHttpRequest(method, uri);
} else if (isOneOf(WITH_ENTITY, method)) {
return new BasicHttpEntityEnclosingRequest(method, uri);
} else {
return super.newHttpRequest(method, uri);
}
}
public static String getNodeIp(URL hubUrl, String sessionId) throws IOException {
final String hubIp = hubUrl.getHost();
final int hubPort = hubUrl.getPort();
HttpHost host = new HttpHost(hubIp, hubPort);
HttpClient client = HttpClientBuilder.create().build();
URL testSessionApi = new URL("http://" + hubIp + ":" + hubPort + "/grid/api/testsession?session=" + sessionId);
BasicHttpEntityEnclosingRequest r = new
BasicHttpEntityEnclosingRequest("POST", testSessionApi.toExternalForm());
HttpResponse response = client.execute(host, r);
JSONObject object = new JSONObject(EntityUtils.toString(response.getEntity()));
return String.valueOf(object.get("proxyId"));
}
public HttpRequest newHttpRequest(final String method, final String uri) throws MethodNotSupportedException {
if (isOneOf(BASIC, method)) {
return new BasicHttpRequest(method, uri);
} else if (isOneOf(WITH_ENTITY, method)) {
return new BasicHttpEntityEnclosingRequest(method, uri);
} else {
return super.newHttpRequest(method, uri);
}
}
/**
* Invokes the given method with the given arguments and invokes the
* {@code JsonRpcCallback} with the result cast to the given
* {@code returnType}, or null if void. The {@code extraHeaders} are added
* to the request.
*
* @param methodName the name of the method to invoke
* @param argument the arguments to the method
* @param extraHeaders extra headers to add to the request
* @param returnType the return type
* @param callback the {@code JsonRpcCallback}
*/
@SuppressWarnings("unchecked")
private <T> Future<T> doInvoke(String methodName, Object argument, Class<T> returnType, Map<String, String> extraHeaders, JsonRpcCallback<T> callback) {
String path = serviceUrl.getPath() + (serviceUrl.getQuery() != null ? "?" + serviceUrl.getQuery() : "");
int port = serviceUrl.getPort() != -1 ? serviceUrl.getPort() : serviceUrl.getDefaultPort();
HttpRequest request = new BasicHttpEntityEnclosingRequest("POST", path);
addHeaders(request, headers);
addHeaders(request, extraHeaders);
try {
writeRequest(methodName, argument, request);
} catch (IOException e) {
callback.onError(e);
}
HttpHost target = new HttpHost(serviceUrl.getHost(), port, serviceUrl.getProtocol());
BasicAsyncRequestProducer asyncRequestProducer = new BasicAsyncRequestProducer(target, request);
BasicAsyncResponseConsumer asyncResponseConsumer = new BasicAsyncResponseConsumer();
RequestAsyncFuture<T> futureCallback = new RequestAsyncFuture<>(returnType, callback);
BasicHttpContext httpContext = new BasicHttpContext();
requester.execute(asyncRequestProducer, asyncResponseConsumer, pool, httpContext, futureCallback);
return (callback instanceof JsonRpcFuture ? (Future<T>) callback : null);
}
private static void getIPOfNode(TestCaseExecution tCExecution) {
try {
Session session = tCExecution.getSession();
HttpCommandExecutor ce = (HttpCommandExecutor) ((RemoteWebDriver) session.getDriver()).getCommandExecutor();
SessionId sessionId = ((RemoteWebDriver) session.getDriver()).getSessionId();
String hostName = ce.getAddressOfRemoteServer().getHost();
int port = ce.getAddressOfRemoteServer().getPort();
HttpHost host = new HttpHost(hostName, port);
HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
URL sessionURL = new URL(RobotServerService.getBaseUrl(session.getHost(), session.getPort()) + "/grid/api/testsession?session=" + sessionId);
BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
HttpResponse response = client.execute(host, r);
if (!response.getStatusLine().toString().contains("403")
&& !response.getEntity().getContentType().getValue().contains("text/html")) {
InputStream contents = response.getEntity().getContent();
StringWriter writer = new StringWriter();
IOUtils.copy(contents, writer, "UTF8");
JSONObject object = new JSONObject(writer.toString());
if (object.has("proxyId")) {
URL myURL = new URL(object.getString("proxyId"));
if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
tCExecution.setRobotHost(myURL.getHost());
tCExecution.setRobotPort(String.valueOf(myURL.getPort()));
}
} else {
LOG.debug("'proxyId' json data not available from remote Selenium Server request : " + writer.toString());
}
}
} catch (IOException | JSONException ex) {
LOG.error(ex.toString(), ex);
}
}
@Test
void serviceShouldNotModifyMessageContent() throws Exception {
urlTestPattern = "/path/to/service/succeeded";
final String originalMessage = MimeMessageUtil.asString(mail.getMessage());
FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
.setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
.setProperty("messageKey", "mKey")
.setProperty("url", "http://" + server.getInetAddress().getHostAddress() + ":"
+ server.getLocalPort() + urlTestPattern)
.build();
mapper.register(urlTestPattern, (request, response, context) -> {
assertThat(request.getRequestLine().getMethod()).isEqualTo("POST");
BasicHttpEntityEnclosingRequest basicRequest = (BasicHttpEntityEnclosingRequest) request;
BasicHttpEntity entity = (BasicHttpEntity) basicRequest.getEntity();
try {
List<NameValuePair> params = URLEncodedUtils.parse(entity);
assertThat(params).hasSize(2).anySatisfy((param) -> {
assertThat(param.getName()).isEqualTo("pKey");
assertThat(param.getValue()).isEqualTo("pValue");
}).anySatisfy((param) -> {
assertThat(param.getName()).isEqualTo("message");
assertThat(param.getValue()).isEqualTo(originalMessage);
});
} finally {
EntityUtils.consume(basicRequest.getEntity());
}
response.setStatusCode(HttpStatus.SC_OK);
});
Mailet mailet = new SerialiseToHTTP();
mailet.init(mailetConfig);
mailet.service(mail);
}
@Test
void serviceShouldNotModifyHeadersContent() throws Exception {
urlTestPattern = "/path/to/service/succeeded";
FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
.setProperty("parameterKey", "pKey").setProperty("parameterValue", "pValue")
.setProperty("url", "http://" + server.getInetAddress().getHostAddress() + ":"
+ server.getLocalPort() + urlTestPattern)
.build();
mapper.register(urlTestPattern, (request, response, context) -> {
assertThat(request.getRequestLine().getMethod()).isEqualTo("POST");
BasicHttpEntityEnclosingRequest basicRequest = (BasicHttpEntityEnclosingRequest) request;
BasicHttpEntity entity = (BasicHttpEntity) basicRequest.getEntity();
try {
List<NameValuePair> params = URLEncodedUtils.parse(entity);
assertThat(params).hasSize(5).anySatisfy((param) -> {
assertThat(param.getName()).isEqualTo("pKey");
assertThat(param.getValue()).isEqualTo("pValue");
}).anySatisfy((param) -> {
assertThat(param.getName()).isEqualTo("subject");
assertThat(param.getValue()).isEqualTo("Fwd: Invitation: (Aucun objet) - "
+ "ven. 20 janv. 2017 14:00 - 15:00 (CET) ([email protected])");
}).anySatisfy((param) -> {
assertThat(param.getName()).isEqualTo("message_id");
assertThat(param.getValue())
.isEqualTo("<[email protected]>");
}).anySatisfy((param) -> {
assertThat(param.getName()).isEqualTo("reply_to");
assertThat(param.getValue()).isEqualTo("[aduprat <[email protected]>]");
}).anySatisfy((param) -> {
assertThat(param.getName()).isEqualTo("size");
assertThat(param.getValue()).isEqualTo("5242");
});
} finally {
EntityUtils.consume(basicRequest.getEntity());
}
response.setStatusCode(HttpStatus.SC_OK);
});
Mailet mailet = new HeadersToHTTP();
mailet.init(mailetConfig);
mailet.service(mail);
}
/**
* Send the specified GET request to the indicated host.
*
* @param hostUrl {@link URL} of target host
* @param request request path (may include parameters)
* @return host response for the specified GET request
* @throws IOException The request triggered an I/O exception
*/
public static HttpResponse getHttpResponse(final URL hostUrl, final String request) throws IOException {
HttpClient client = HttpClientBuilder.create().build();
URL sessionURL = new URL(hostUrl.getProtocol(), hostUrl.getAuthority(), request);
BasicHttpEntityEnclosingRequest basicHttpEntityEnclosingRequest =
new BasicHttpEntityEnclosingRequest("GET", sessionURL.toExternalForm());
return client.execute(extractHost(hostUrl), basicHttpEntityEnclosingRequest);
}