Here are the examples of the java api org.apache.http.client.methods.CloseableHttpResponse taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2416 Examples
19
Source : InitializrServiceTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
@Test
public void loadMetadataInvalidJson() throws Exception {
CloseableHttpResponse response = mock(CloseableHttpResponse.clreplaced);
mockHttpEnreplacedy(response, "Foo-Bar-Not-JSON".getBytes(), "application/json");
mockStatus(response, 200);
given(this.http.execute(isA(HttpGet.clreplaced))).willReturn(response);
ProjectGenerationRequest request = new ProjectGenerationRequest();
replacedertThatExceptionOfType(ReportableException.clreplaced).isThrownBy(() -> this.invoker.generate(request)).withMessageContaining("Invalid content received from server");
}
19
Source : InitializrServiceTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
@Test
public void generateProjectNoContent() throws Exception {
mockSuccessfulMetadataGet(false);
CloseableHttpResponse response = mock(CloseableHttpResponse.clreplaced);
mockStatus(response, 500);
given(this.http.execute(isA(HttpGet.clreplaced))).willReturn(response);
ProjectGenerationRequest request = new ProjectGenerationRequest();
replacedertThatExceptionOfType(ReportableException.clreplaced).isThrownBy(() -> this.invoker.generate(request)).withMessageContaining("No content received from server");
}
19
Source : InitializrServiceTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
@Test
public void loadMetadataNoContent() throws Exception {
CloseableHttpResponse response = mock(CloseableHttpResponse.clreplaced);
mockStatus(response, 500);
given(this.http.execute(isA(HttpGet.clreplaced))).willReturn(response);
ProjectGenerationRequest request = new ProjectGenerationRequest();
replacedertThatExceptionOfType(ReportableException.clreplaced).isThrownBy(() -> this.invoker.generate(request)).withMessageContaining("No content received from server");
}
19
Source : AbstractHttpClientMockTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
protected void mockSuccessfulMetadataGet(String contentPath, String contentType, boolean serviceCapabilities) throws IOException {
CloseableHttpResponse response = mock(CloseableHttpResponse.clreplaced);
byte[] content = readClreplacedpathResource(contentPath);
mockHttpEnreplacedy(response, content, contentType);
mockStatus(response, 200);
given(this.http.execute(argThat(getForMetadata(serviceCapabilities)))).willReturn(response);
}
19
Source : AbstractHttpClientMockTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
protected void mockMetadataGetError(int status, String message) throws IOException, JSONException {
CloseableHttpResponse response = mock(CloseableHttpResponse.clreplaced);
mockHttpEnreplacedy(response, createJsonError(status, message).getBytes(), "application/json");
mockStatus(response, status);
given(this.http.execute(isA(HttpGet.clreplaced))).willReturn(response);
}
19
Source : AbstractHttpClientMockTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
protected void mockProjectGenerationError(int status, String message) throws IOException, JSONException {
// Required for project generation as the metadata is read first
mockSuccessfulMetadataGet(false);
CloseableHttpResponse response = mock(CloseableHttpResponse.clreplaced);
mockHttpEnreplacedy(response, createJsonError(status, message).getBytes(), "application/json");
mockStatus(response, status);
given(this.http.execute(isA(HttpGet.clreplaced))).willReturn(response);
}
19
Source : InitializrService.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
private void validateResponse(CloseableHttpResponse httpResponse, String serviceUrl) {
if (httpResponse.getEnreplacedy() == null) {
throw new ReportableException("No content received from server '" + serviceUrl + "'");
}
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw createException(serviceUrl, httpResponse);
}
}
19
Source : HttpClientUtils.java
with MIT License
from YeautyYE
with MIT License
from YeautyYE
public static List<String> cookiesByGet(String url, String userAgent, String referer, String cookie) throws IOException {
HttpClientBuilder builder = HttpClients.custom();
CloseableHttpClient client = builder.build();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Host", getHost(url));
if (referer != null) {
httpGet.addHeader("Referer", referer);
}
httpGet.addHeader("User-Agent", userAgent);
if (cookie != null) {
httpGet.addHeader("Cookie", cookie);
}
List<String> resultList = new LinkedList<>();
CloseableHttpResponse response = client.execute(httpGet);
for (Header header : response.getAllHeaders()) {
if ("Set-Cookie".equals(header.getName())) {
HeaderElement[] elements = header.getElements();
resultList.add(elements[0].toString().split(";")[0]);
}
}
if (resultList != null && resultList.size() > 0) {
return resultList;
} else {
return null;
}
}
19
Source : HttpClientImpl.java
with GNU Lesser General Public License v3.0
from xkcoding
with GNU Lesser General Public License v3.0
from xkcoding
private boolean isSuccess(CloseableHttpResponse response) {
if (response == null) {
return false;
}
if (response.getStatusLine() == null) {
return false;
}
return response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300;
}
19
Source : RdbmsMandatoryAccessControlForExchangesTest.java
with Apache License 2.0
from wso2-attic
with Apache License 2.0
from wso2-attic
@Parameters({ "admin-username", "admin-preplacedword" })
@Test(description = "retrieve exchange details by a user who has exchanges:get scope")
public void testGetExchangeByAdminUser(String username, String preplacedword) throws Exception {
HttpGet httpGet = new HttpGet(apiBasePath + "/exchanges");
ClientHelper.setAuthHeader(httpGet, username, preplacedword);
CloseableHttpResponse response = client.execute(httpGet);
replacedert.replacedertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
}
19
Source : RdbmsMandatoryAccessControlForExchangesTest.java
with Apache License 2.0
from wso2-attic
with Apache License 2.0
from wso2-attic
@Parameters({ "test-username", "test-preplacedword" })
@Test(description = "retrieve exchange details by a user who does not have exchanges:get scope")
public void testGetExchangeByTestUser(String username, String preplacedword) throws Exception {
HttpGet httpGet = new HttpGet(apiBasePath + "/exchanges");
ClientHelper.setAuthHeader(httpGet, username, preplacedword);
CloseableHttpResponse response = client.execute(httpGet);
replacedert.replacedertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_FORBIDDEN);
}
19
Source : HeartBeatComponent.java
with Apache License 2.0
from wso2
with Apache License 2.0
from wso2
public static JsonObject getJsonResponse(CloseableHttpResponse response) {
String stringResponse = getStringResponse(response);
return new JsonParser().parse(stringResponse).getAsJsonObject();
}
19
Source : WechatPay2Validator.java
with Apache License 2.0
from wechatpay-apiv3
with Apache License 2.0
from wechatpay-apiv3
protected final String buildMessage(CloseableHttpResponse response) throws IOException {
String timestamp = response.getFirstHeader("Wechatpay-Timestamp").getValue();
String nonce = response.getFirstHeader("Wechatpay-Nonce").getValue();
String body = getResponseBody(response);
return timestamp + "\n" + nonce + "\n" + body + "\n";
}
19
Source : SentryApiClient.java
with MIT License
from vostok
with MIT License
from vostok
private static int extractStatusCode(CloseableHttpResponse response) {
return response.getStatusLine().getStatusCode();
}
19
Source : SentryApiClient.java
with MIT License
from vostok
with MIT License
from vostok
private static boolean isErrorResponse(CloseableHttpResponse response) {
return 400 <= extractStatusCode(response);
}
19
Source : CloseableHttpClientMock.java
with MIT License
from vostok
with MIT License
from vostok
/**
* @author Daniil Zhenikhov
*/
public clreplaced CloseableHttpClientMock extends CloseableHttpClient {
private static final String PING_METHOD = "/ping";
private static final String OK_200_ADDR = "ok_2xx" + PING_METHOD;
private static final String ERROR_4XX_ADDR = "error_4xx" + PING_METHOD;
private static final String ERROR_5XX_ADDR = "error_5xx" + PING_METHOD;
private static final String ERROR_5XX_ADDR_PROCESSING_TEST = "error_5xx_processing_test" + PING_METHOD;
private static final CloseableHttpResponse OK_200;
private static final CloseableHttpResponse ERROR_4XX;
private static final CloseableHttpResponse ERROR_5XX;
private static final CloseableHttpResponse ERROR_5XX_PROCESSING_TEST;
static {
OK_200 = Mockito.mock(CloseableHttpResponse.clreplaced);
StatusLine statusLine200 = Mockito.mock(StatusLine.clreplaced);
ERROR_4XX = Mockito.mock(CloseableHttpResponse.clreplaced);
StatusLine statusLine4xx = Mockito.mock(StatusLine.clreplaced);
ERROR_5XX = Mockito.mock(CloseableHttpResponse.clreplaced);
StatusLine statusLine5xx = Mockito.mock(StatusLine.clreplaced);
ERROR_5XX_PROCESSING_TEST = Mockito.mock(CloseableHttpResponse.clreplaced);
StatusLine statusLine5xxTimeTest = Mockito.mock(StatusLine.clreplaced);
Mockito.when(OK_200.getStatusLine()).thenReturn(statusLine200);
Mockito.when(statusLine200.getStatusCode()).thenReturn(200);
Mockito.when(ERROR_4XX.getStatusLine()).thenReturn(statusLine4xx);
Mockito.when(statusLine4xx.getStatusCode()).thenReturn(400);
Mockito.when(ERROR_5XX.getStatusLine()).thenReturn(statusLine5xx);
Mockito.when(statusLine5xx.getStatusCode()).thenReturn(500);
Mockito.when(ERROR_5XX_PROCESSING_TEST.getStatusLine()).thenReturn(statusLine5xxTimeTest);
Mockito.when(statusLine5xxTimeTest.getStatusCode()).thenReturn(500);
}
@Override
protected CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, HttpContext context) throws IOException {
switch(request.getRequestLine().getUri()) {
case OK_200_ADDR:
return OK_200;
case ERROR_4XX_ADDR:
return ERROR_4XX;
case ERROR_5XX_ADDR:
return ERROR_5XX;
case ERROR_5XX_ADDR_PROCESSING_TEST:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return ERROR_5XX_PROCESSING_TEST;
default:
throw new IOException();
}
}
@Override
public void close() {
}
@Override
public HttpParams getParams() {
return null;
}
@Override
public ClientConnectionManager getConnectionManager() {
return null;
}
}
19
Source : TimelineApiClient.java
with MIT License
from vostok
with MIT License
from vostok
/**
* @return true if ping was performed without errors
*/
public boolean ping() {
HttpGet httpGet = new HttpGet(server.resolve(Resources.PING));
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
return 200 == response.getStatusLine().getStatusCode();
} catch (IOException e) {
return false;
}
}
19
Source : ApacheWire.java
with MIT License
from Vatavuk
with MIT License
from Vatavuk
@Override
public final Dict send(final Dict request) throws IOException {
final Dict message = new JoinedDict(request, this.parameters);
try (CloseableHttpResponse response = this.client.execute(message)) {
final StatusLine status = response.getStatusLine();
return new DictOf(new Method(new Method.Of(message).replacedtring()), new RequestUri(new RequestUri.Of(message).uri().getPath()), new Status(status.getStatusCode()), new ReasonPhrase(status.getReasonPhrase()), new Body(ApacheWire.fetchBody(response)), new ApacheHeaders(response.getAllHeaders()));
}
}
19
Source : Http.java
with Apache License 2.0
from ucloud
with Apache License 2.0
from ucloud
private boolean statusOK(CloseableHttpResponse response) {
boolean ok = false;
if (response != null) {
ok = response.getStatusLine().getStatusCode() == 200;
}
return ok;
}
19
Source : SimpleHttpClient.java
with Apache License 2.0
from ucarGroup
with Apache License 2.0
from ucarGroup
public static String get(String url) throws Exception {
HttpRequestBase request = new HttpGet(url);
HttpEnreplacedy enreplacedy = null;
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
if (response == null || response.getStatusLine() == null) {
throw new ElasticSearchException("get http line error");
}
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 401) {
throw new ElasticAuthException("401 authority error:username or preplacedword not correct");
} else if (statusCode == 403) {
throw new ElasticAuthException("403 pemission error:you have right to take current option");
}
enreplacedy = response.getEnreplacedy();
String result = null;
if (enreplacedy != null) {
result = EnreplacedyUtils.toString(enreplacedy, "UTF-8");
} else {
result = String.valueOf(response.getStatusLine());
}
return result;
} catch (Exception e) {
throw e;
} finally {
try {
EnreplacedyUtils.consume(enreplacedy);
} catch (IOException e) {
LOGGER.error("", e);
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
LOGGER.error("连接关闭失败:", e);
}
}
if (request != null) {
request.releaseConnection();
}
}
}
19
Source : HTTP.java
with Apache License 2.0
from tlw-ray
with Apache License 2.0
from tlw-ray
protected Header[] searchForHeaders(CloseableHttpResponse response) {
return response.getAllHeaders();
}
19
Source : SiteStatisticsFunctionalTest.java
with Apache License 2.0
from terracotta-bank
with Apache License 2.0
from terracotta-bank
@Test
public void testAdminLoginForPrivilegeEscalation() throws Exception {
String jsessionIdCookie = http.session();
// attempt to register the system user
try (CloseableHttpResponse response = http.post(post("/register").addParameter("registerUsername", "system").addParameter("registerPreplacedword", "preplacedword").addParameter("registerEmail", "[email protected]").addParameter("registerName", "Backdoor Registration"))) {
}
// can I get to the backoffice pages now?
try (CloseableHttpResponse response = http.getForEnreplacedy(get("/siteStatistics").addHeader("Cookie", jsessionIdCookie))) {
replacedert.replacedertEquals(403, response.getStatusLine().getStatusCode());
}
}
19
Source : ContentParsingFilterVTests.java
with Apache License 2.0
from terracotta-bank
with Apache License 2.0
from terracotta-bank
// This test will launch "calc.exe" on your local machine
@Test(enabled = false)
public void testJavaRce() throws IOException {
try (InputStream payload = xml("serialization/rce.out")) {
BasicHttpEnreplacedy body = new BasicHttpEnreplacedy();
body.setContent(payload);
try (CloseableHttpResponse response = this.http.post(post("/login").setHeader("Content-Type", "application/octet-stream").setEnreplacedy(body))) {
}
}
}
19
Source : ContentParsingFilterVTests.java
with Apache License 2.0
from terracotta-bank
with Apache License 2.0
from terracotta-bank
// This test will launch "calc.exe" on your local machine
@Test(enabled = false)
public void testJsonRce() throws IOException {
BasicHttpEnreplacedy body = new BasicHttpEnreplacedy();
body.setContent(xml("serialization/rce.json"));
try (CloseableHttpResponse response = this.http.post(post("/login").setHeader("Content-Type", "application/json").setEnreplacedy(body))) {
}
}
19
Source : AdminLoginFunctionalTest.java
with Apache License 2.0
from terracotta-bank
with Apache License 2.0
from terracotta-bank
@Test(groups = "bruteforce")
public void testAdminLoginForBackdoor() throws Exception {
try (CloseableHttpResponse response = http.post(post("/adminLogin").addParameter("username", "anyusername").addParameter("preplacedword", "backoffice"))) {
replacedert.replacedertEquals(401, response.getStatusLine().getStatusCode());
}
}
19
Source : HttpClientHelper.java
with Apache License 2.0
from TeamvisionCorp
with Apache License 2.0
from TeamvisionCorp
/**
* @param url http url
* @return CloseableHttpResponse
* @throws ClientProtocolException
* @throws Exception
*/
private static CloseableHttpResponse getmethod(String url) throws ClientProtocolException, Exception {
HttpClientHelper.createClient();
HttpClientHelper.createContext();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet, context);
return response;
}
19
Source : TransmissionService.java
with MIT License
from tarpha
with MIT License
from tarpha
public boolean initialize() {
username = settingService.getSettingValue("TRANSMISSION_USERNAME");
try {
preplacedword = cryptoService.decrypt(settingService.getSettingValue("TRANSMISSION_PreplacedWORD"));
} catch (UnsupportedEncodingException | GeneralSecurityException e) {
log.error(e.getMessage());
}
baseUrl = "http://" + settingService.getSettingValue("TRANSMISSION_HOST") + ":" + settingService.getSettingValue("TRANSMISSION_PORT") + "/transmission/rpc";
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePreplacedwordCredentials credentials = new UsernamePreplacedwordCredentials(username, preplacedword);
provider.setCredentials(AuthScope.ANY, credentials);
if (StringUtils.isEmpty(xTransmissionSessionId)) {
CloseableHttpResponse response = null;
try {
httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
response = httpClient.execute(new HttpGet(baseUrl));
xTransmissionSessionId = response.getFirstHeader("X-Transmission-Session-Id").getValue();
} catch (IOException e) {
log.error(e.getMessage());
} finally {
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpClient);
}
}
List<Header> headers = new ArrayList<Header>();
headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
headers.add(new BasicHeader("X-Transmission-Session-Id", xTransmissionSessionId));
httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).setDefaultHeaders(headers).build();
if (StringUtils.isEmpty(xTransmissionSessionId)) {
return false;
}
return true;
}
19
Source : RestClient.java
with Apache License 2.0
from tal-tech
with Apache License 2.0
from tal-tech
/**
* 执行HTTP请求
* @param request
* @return
*/
protected HttpResponse _execute(HttpUriRequest request) {
CloseableHttpResponse response = null;
if (httpClient != null && request != null) {
try {
response = httpClient.execute(request);
} catch (ClientProtocolException e) {
log.error(String.format("%S \"%s\" failed: ", request.getMethod(), request.getURI()), e);
} catch (IOException e) {
log.error(String.format("%S \"%s\" failed: ", request.getMethod(), request.getURI()), e);
}
}
return response;
}
19
Source : QAInMemoryByzantineDefaultsAuthenticated.java
with Apache License 2.0
from srotya
with Apache License 2.0
from srotya
@Test
public void testUnauthenticatedRequests() throws Exception {
CloseableHttpResponse response = TestUtils.makeRequest(new HttpGet("http://localhost:" + PORT + "/databases/_internal"));
replacedertEquals(401, response.getStatusLine().getStatusCode());
response = TestUtils.makeRequest(new HttpGet("http://localhost:" + PORT + "/databases/_internal2"));
replacedertEquals(401, response.getStatusLine().getStatusCode());
}
19
Source : P2ProxyIT.java
with Eclipse Public License 1.0
from sonatype-nexus-community
with Eclipse Public License 1.0
from sonatype-nexus-community
private static void replacedertMissing(final P2Client client, final String path) throws IOException {
try (CloseableHttpResponse response = client.get(path)) {
replacedertThat(status(response), is(HttpStatus.NOT_FOUND));
}
}
19
Source : YoutubeSignatureCipherManager.java
with Apache License 2.0
from sedmelluq
with Apache License 2.0
from sedmelluq
private void validateResponseCode(String cipherScriptUrl, CloseableHttpResponse response) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (!HttpClientTools.isSuccessWithContent(statusCode)) {
throw new IOException("Received non-success response code " + statusCode + " from script url " + cipherScriptUrl + " ( " + parseTokenScriptUrl(cipherScriptUrl) + " )");
}
}
19
Source : ClientResponse.java
with Apache License 2.0
from rockscript
with Apache License 2.0
from rockscript
/**
* Obtain a response by starting from the {@link HttpClient} object
* use one of the newXxx methods to get a request and then
* invoke {@link ClientRequest#execute()}
*/
public clreplaced ClientResponse {
/**
* transient because this field should not be serialized by gson
*/
transient ClientRequest request;
/**
* transient because this field should not be serialized by gson
*/
transient CloseableHttpResponse apacheResponse;
protected int status;
protected Map<String, List<String>> headers;
protected String body;
protected ClientResponse(ClientRequest request) throws IOException {
this.request = request;
this.apacheResponse = request.httpClient.apacheHttpClient.execute(request.apacheRequest);
try {
this.status = apacheResponse.getStatusLine().getStatusCode();
this.headers = extractHeaders(apacheResponse);
HttpEnreplacedy enreplacedy = apacheResponse.getEnreplacedy();
if (enreplacedy != null) {
try {
String charset = getContentTypeCharset("UTF-8");
InputStream content = enreplacedy.getContent();
this.body = Io.getString(content, charset);
} catch (Exception e) {
throw new RuntimeException("Couldn't ready body/enreplacedy from http request " + toString(), e);
}
}
} finally {
apacheResponse.close();
}
}
static Map<String, List<String>> extractHeaders(org.apache.http.HttpResponse apacheResponse) {
Map<String, List<String>> headers = new LinkedHashMap<>();
Header[] allHeaders = apacheResponse.getAllHeaders();
if (allHeaders != null) {
for (Header header : allHeaders) {
headers.computeIfAbsent(header.getName(), key -> new ArrayList<>()).add(header.getValue());
}
}
return headers;
}
@Override
public String toString() {
return toString(null);
}
public String toString(String prefix) {
return toString(prefix, Integer.MAX_VALUE);
}
public String toString(String prefix, int maxBodyLength) {
if (prefix == null) {
prefix = "";
}
StringBuilder text = new StringBuilder();
text.append(prefix);
text.append("< ");
text.append(apacheResponse.getStatusLine());
if (headers != null) {
for (String headerName : headers.keySet()) {
if (headerName != null) {
List<String> headerListValue = headers.get(headerName);
String headerValue = headerListToString(headerListValue);
text.append(NEWLINE);
text.append(prefix);
text.append(" ");
text.append(headerName);
text.append(": ");
text.append(headerValue);
}
}
} else {
text.append(NEWLINE);
text.append(prefix);
text.append("< ");
text.append(status);
}
if (body != null) {
text.append(NEWLINE);
text.append(prefix);
text.append(" ");
String bodyCustomized = getString(body, prefix, maxBodyLength);
text.append(bodyCustomized);
}
return text.toString();
}
static String getString(String bodyText, String prefix, int maxBodyLength) {
return new BufferedReader(new StringReader(bodyText)).lines().map(line -> (line.length() > maxBodyLength ? line.substring(0, maxBodyLength) + "..." : line)).collect(Collectors.joining("\n" + (prefix != null ? prefix + " " : " ")));
}
public static String headerListToString(List<String> headerListValue) {
return headerListValue.stream().collect(Collectors.joining(";"));
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public ClientResponse replacedertStatusOk() {
return replacedertStatus(Http.ResponseCodes.OK_200);
}
public ClientResponse replacedertStatusBadRequest() {
return replacedertStatus(Http.ResponseCodes.BAD_REQUEST_400);
}
public ClientResponse replacedertStatusNotFound() {
return replacedertStatus(Http.ResponseCodes.NOT_FOUND_404);
}
public ClientResponse replacedertStatusInternalServerException() {
return replacedertStatus(Http.ResponseCodes.INTERNAL_SERVER_ERROR_500);
}
public ClientResponse replacedertStatus(int expectedStatus) {
if (status != expectedStatus) {
throw new RuntimeException("Status was " + status + ", expected " + expectedStatus);
}
return this;
}
public String getBody() {
return body;
}
@SuppressWarnings("unchecked")
public <T> T getBodyAs(Type type) {
return (T) request.getHttpClient().getGson().fromJson(body, type);
}
@SuppressWarnings("unchecked")
public <T> T getBodyAs(Clreplaced<T> type) {
return getBodyAs((Type) type);
}
public void setHeaders(Map<String, List<String>> headers) {
this.headers = headers;
}
public boolean isContentTypeApplicationJson() {
return headerContains(Http.Headers.CONTENT_TYPE, Http.ContentTypes.APPLICATION_JSON) || headerContains(Http.Headers.CONTENT_TYPE, Http.ContentTypes.APPLICATION_LD_JSON);
}
public boolean headerContains(String headerName, String headerValue) {
if (headers == null) {
return false;
}
List<String> headerValues = headers.get(headerName);
if (headerValues == null) {
return false;
}
for (String actualValue : headerValues) {
if (actualValue.contains(headerValue)) {
return true;
}
}
return false;
}
public ClientRequest getRequest() {
return request;
}
public CloseableHttpResponse getApacheResponse() {
return apacheResponse;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public List<String> getHeader(String headerName) {
if (headers != null) {
return headers.get(Http.Headers.CONTENT_TYPE);
}
return null;
}
public String getContentTypeCharset(String defaultCharset) {
List<String> values = getHeader(Http.Headers.CONTENT_TYPE);
if (values != null) {
for (String value : values) {
HeaderElement[] headerElements = BasicHeaderValueParser.parseElements(value, (HeaderValueParser) null);
if (headerElements != null && headerElements.length > 0) {
NameValuePair charsetPair = headerElements[0].getParameterByName("charset");
if (charsetPair != null) {
return charsetPair.getValue();
}
}
}
}
return defaultCharset;
}
public void setBody(String body) {
this.body = body;
}
}
19
Source : HttpClientMockBuilder_doReturnWithStatusTest.java
with MIT License
from PawelAdamski
with MIT License
from PawelAdamski
@ParameterizedTest
@ValueSource(ints = { 200, 300, 400, 500 })
public void doReturn_should_set_response_status_empty_reason_and_null_enreplacedy_when_only_statusCode_is_provided(int statusCode) throws IOException {
HttpClientMock httpClientMock = new HttpClientMock();
httpClientMock.onGet().doReturnWithStatus(statusCode);
CloseableHttpResponse response = httpClientMock.execute(httpGet("http://localhost"));
replacedertThat(response, hreplacedtatus(statusCode));
replacedertThat(response, hasNoEnreplacedy());
}
19
Source : HttpClientMockBuilder_doReturnStatusTest.java
with MIT License
from PawelAdamski
with MIT License
from PawelAdamski
@ParameterizedTest
@ValueSource(ints = { 200, 300, 400, 500 })
public void doReturnStatus_should_set_response_status_and_empty_enreplacedy(int statusCode) throws IOException {
HttpClientMock httpClientMock = new HttpClientMock();
httpClientMock.onGet().doReturnStatus(statusCode);
CloseableHttpResponse response = httpClientMock.execute(httpGet("http://localhost"));
replacedertThat(response, hreplacedtatus(statusCode));
replacedertThat(response, hasContent(""));
}
19
Source : JsonHttpProtocol.java
with Apache License 2.0
from opendistro-for-elasticsearch
with Apache License 2.0
from opendistro-for-elasticsearch
@Override
public QueryResponse execute(QueryRequest request) throws ResponseException, IOException {
try (CloseableHttpResponse response = transport.doPost(sqlContextPath, defaultJsonHeaders, defaultJdbcParams, buildQueryRequestBody(request), 0)) {
return jsonHttpResponseHandler.handleResponse(response, this::processQueryResponse);
}
}
19
Source : JsonHttpProtocol.java
with Apache License 2.0
from opendistro-for-elasticsearch
with Apache License 2.0
from opendistro-for-elasticsearch
@Override
public ConnectionResponse connect(int timeout) throws ResponseException, IOException {
try (CloseableHttpResponse response = transport.doGet("/", defaultEmptyRequestBodyJsonHeaders, null, timeout)) {
return jsonHttpResponseHandler.handleResponse(response, this::processConnectionResponse);
}
}
19
Source : JsonCursorHttpProtocol.java
with Apache License 2.0
from opendistro-for-elasticsearch
with Apache License 2.0
from opendistro-for-elasticsearch
@Override
public QueryResponse execute(QueryRequest request) throws ResponseException, IOException {
try (CloseableHttpResponse response = getTransport().doPost(getSqlContextPath(), defaultJsonHeaders, defaultJdbcParams, buildQueryRequestBody(request), 0)) {
return getJsonHttpResponseHandler().handleResponse(response, this::processQueryResponse);
}
}
19
Source : HttpWriter.java
with Apache License 2.0
from olacabs
with Apache License 2.0
from olacabs
/**
* creates a response map that can be set in the new event set.
*
* @param event event to be added in the response
* @param response http response
* @param httpMethodType the http method type
* @return req
*/
private Map<String, Object> createResponseMap(Event event, CloseableHttpResponse response, String httpMethodType) throws IOException {
return ImmutableMap.of("SourceEvent", event.getJsonNode(), "HttpMethod", httpMethodType, "HttpResponseCode", response.getStatusLine().getStatusCode(), "HttpResponse", getResponseAsJson(response));
}
19
Source : TestHttpClientAdapter.java
with GNU General Public License v2.0
from mguessan
with GNU General Public License v2.0
from mguessan
public void testBasicGetRequest() throws IOException {
try (HttpClientAdapter httpClientAdapter = new HttpClientAdapter("http://davmail.sourceforge.net/version.txt")) {
HttpGet httpget = new HttpGet("http://davmail.sourceforge.net/version.txt");
try (CloseableHttpResponse response = httpClientAdapter.execute(httpget)) {
String responseString = new BasicResponseHandler().handleResponse(response);
replacedertNotNull(responseString);
System.out.println(responseString);
}
// alternative with GetRequest
GetRequest getRequest = new GetRequest("http://davmail.sourceforge.net/version.txt");
String responseString = httpClientAdapter.executeGetRequest(getRequest);
replacedertNotNull(responseString);
}
}
19
Source : TestHttpClient4.java
with GNU General Public License v2.0
from mguessan
with GNU General Public License v2.0
from mguessan
public void testBasicGetRequest() throws IOException {
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
try (CloseableHttpClient httpClient = clientBuilder.build()) {
HttpGet httpget = new HttpGet("http://davmail.sourceforge.net/version.txt");
try (CloseableHttpResponse response = httpClient.execute(httpget)) {
String responseString = new BasicResponseHandler().handleResponse(response);
System.out.println(responseString);
}
}
}
19
Source : TestCaldavHttpClient4.java
with GNU General Public License v2.0
from mguessan
with GNU General Public License v2.0
from mguessan
public void testGetOtherUserCalendar() throws IOException {
HttpPropfind method = new HttpPropfind("/principals/users/" + Settings.getProperty("davmail.usera"), DavConstants.PROPFIND_ALL_PROP, new DavPropertyNameSet(), DavConstants.DEPTH_INFINITY);
try (CloseableHttpResponse response = httpClient.execute(method)) {
replacedertEquals(HttpStatus.SC_MULTI_STATUS, response.getStatusLine().getStatusCode());
}
}
19
Source : TestCaldavHttpClient4.java
with GNU General Public License v2.0
from mguessan
with GNU General Public License v2.0
from mguessan
public void testGetInbox() throws IOException {
HttpGet method = new HttpGet("/users/" + session.getEmail() + "/inbox/");
try (CloseableHttpResponse response = httpClient.execute(method)) {
replacedertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
}
}
19
Source : TestCaldavHttpClient4.java
with GNU General Public License v2.0
from mguessan
with GNU General Public License v2.0
from mguessan
public void testGetUserRoot() throws IOException {
HttpGet method = new HttpGet("/users/" + session.getEmail() + '/');
try (CloseableHttpResponse response = httpClient.execute(method)) {
replacedertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
}
}
19
Source : TestCaldavHttpClient4.java
with GNU General Public License v2.0
from mguessan
with GNU General Public License v2.0
from mguessan
public void testPropfindCalendar() throws IOException {
HttpPropfind method = new HttpPropfind("/users/" + session.getEmail() + "/calendar/", null, 1);
try (CloseableHttpResponse response = httpClient.execute(method)) {
replacedertEquals(HttpStatus.SC_MULTI_STATUS, response.getStatusLine().getStatusCode());
}
}
19
Source : TestCaldavHttpClient4.java
with GNU General Public License v2.0
from mguessan
with GNU General Public License v2.0
from mguessan
public void testGetRoot() throws IOException {
HttpGet method = new HttpGet("/");
try (CloseableHttpResponse response = httpClient.execute(method)) {
replacedertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
}
}
19
Source : TestCaldavHttpClient4.java
with GNU General Public License v2.0
from mguessan
with GNU General Public License v2.0
from mguessan
public void testGetContacts() throws IOException {
HttpGet method = new HttpGet("/users/" + session.getEmail() + "/contacts/");
try (CloseableHttpResponse response = httpClient.execute(method)) {
replacedertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
}
}
19
Source : TestCaldavHttpClient4.java
with GNU General Public License v2.0
from mguessan
with GNU General Public License v2.0
from mguessan
public void testGetCalendar() throws IOException {
HttpGet method = new HttpGet("/users/" + session.getEmail() + "/calendar/");
try (CloseableHttpResponse response = httpClient.execute(method)) {
replacedertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
}
}
19
Source : HttpClientAdapter.java
with GNU General Public License v2.0
from mguessan
with GNU General Public License v2.0
from mguessan
/**
* Execute get request and return response body as string.
*
* @param getRequest get request
* @return response body
* @throws IOException on error
*/
public String executeGetRequest(GetRequest getRequest) throws IOException {
handleURI(getRequest);
String responseBodyreplacedtring;
try (CloseableHttpResponse response = execute(getRequest)) {
responseBodyreplacedtring = getRequest.handleResponse(response);
}
return responseBodyreplacedtring;
}
19
Source : HttpResponseContent.java
with Apache License 2.0
from landy8530
with Apache License 2.0
from landy8530
/**
* @author landyl
* @create 10:29 08/23/2019
*/
public clreplaced HttpResponseContent {
private String encoding;
private byte[] contentBytes;
private int statusCode;
private String contentType;
private String contentTypeString;
private CloseableHttpResponse originalResponse;
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public byte[] getContentBytes() {
return contentBytes;
}
public void setContentBytes(byte[] contentBytes) {
this.contentBytes = contentBytes;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getContentTypeString() {
return contentTypeString;
}
public void setContentTypeString(String contentTypeString) {
this.contentTypeString = contentTypeString;
}
public String getContent() {
return this.getContent(this.encoding);
}
public String getContent(String encoding) {
if (encoding == null) {
return new String(this.contentBytes);
} else {
try {
return new String(this.contentBytes, encoding);
} catch (Exception ex) {
return "";
}
}
}
public CloseableHttpResponse getOriginalResponse() {
return originalResponse;
}
public void setOriginalResponse(CloseableHttpResponse originalResponse) {
this.originalResponse = originalResponse;
}
}
19
Source : HttpResponseContent.java
with Apache License 2.0
from landy8530
with Apache License 2.0
from landy8530
public void setOriginalResponse(CloseableHttpResponse originalResponse) {
this.originalResponse = originalResponse;
}
See More Examples