本文整理了Java中org.apache.http.client.methods.CloseableHttpResponse.getEntity()
方法的一些代码示例,展示了CloseableHttpResponse.getEntity()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。CloseableHttpResponse.getEntity()
方法的具体详情如下:
包路径:org.apache.http.client.methods.CloseableHttpResponse
类名称:CloseableHttpResponse
方法名:getEntity
暂无
代码示例来源:origin: gocd/gocd
private String responseBody(CloseableHttpResponse response) throws IOException {
try (InputStream is = response.getEntity() == null ? new NullInputStream(0) : response.getEntity().getContent()) {
return IOUtils.toString(is, StandardCharsets.UTF_8);
}
}
代码示例来源:origin: apache/incubator-gobblin
/**
* Default implementation where any status code equal to or greater than 400 is regarded as a failure.
* {@inheritDoc}
* @see org.apache.gobblin.writer.http.HttpWriterDecoration#processResponse(org.apache.http.HttpResponse)
*/
@Override
public void processResponse(CloseableHttpResponse response) throws IOException, UnexpectedResponseException {
if (response.getStatusLine().getStatusCode() >= 400) {
if (response.getEntity() != null) {
throw new RuntimeException("Failed. " + EntityUtils.toString(response.getEntity())
+ " , response: " + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE));
}
throw new RuntimeException("Failed. Response: " + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE));
}
}
代码示例来源:origin: medcl/elasticsearch-analysis-ik
CloseableHttpResponse response;
BufferedReader in;
HttpGet get = new HttpGet(location);
get.setConfig(rc);
try {
response = httpclient.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
if (response.getEntity().getContentType().getValue().contains("charset=")) {
String contentType = response.getEntity().getContentType().getValue();
charset = contentType.substring(contentType.lastIndexOf("=") + 1);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset));
String line;
while ((line = in.readLine()) != null) {
response.close();
return buffer;
response.close();
} catch (ClientProtocolException e) {
logger.error("getRemoteWords {} error", e, location);
代码示例来源:origin: stackoverflow.com
File myFile = new File("mystuff.bin");
CloseableHttpClient client = HttpClients.createDefault();
try (CloseableHttpResponse response = client.execute(new HttpGet("http://host/stuff"))) {
HttpEntity entity = response.getEntity();
if (entity != null) {
try (FileOutputStream outstream = new FileOutputStream(myFile)) {
entity.writeTo(outstream);
}
}
}
代码示例来源:origin: opensourceBIM/BIMserver
public static ObjectNode post(String url, ObjectNode objectNode) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OBJECT_MAPPER.writeValue(out, objectNode);
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new ByteArrayEntity(out.toByteArray(), ContentType.APPLICATION_JSON));
CloseableHttpResponse httpResponse = httpclient.execute(post);
ObjectNode response = OBJECT_MAPPER.readValue(httpResponse.getEntity().getContent(), ObjectNode.class);
return response;
} finally {
httpclient.close();
}
}
}
代码示例来源:origin: line/armeria
@Test
public void echoPost() throws Exception {
try (CloseableHttpClient hc = HttpClients.createMinimal()) {
final HttpPost post = new HttpPost(server().uri("/jsp/echo_post.jsp"));
post.setEntity(new StringEntity("test"));
try (CloseableHttpResponse res = hc.execute(post)) {
assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue())
.startsWith("text/html");
final String actualContent = CR_OR_LF.matcher(EntityUtils.toString(res.getEntity()))
.replaceAll("");
assertThat(actualContent).isEqualTo(
"<html><body>" +
"<p>Check request body</p>" +
"<p>test</p>" +
"</body></html>");
}
}
}
代码示例来源:origin: stackoverflow.com
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);
// This attaches the file to the POST:
File f = new File("[/path/to/upload]");
builder.addBinaryBody(
"file",
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
代码示例来源:origin: alibaba/jstorm
private boolean httpPost(String url, String msg) {
boolean ret = false;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
try {
HttpPost request = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("name", monitorName));
nvps.add(new BasicNameValuePair("msg", msg));
request.setEntity(new UrlEncodedFormEntity(nvps));
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
LOG.info(EntityUtils.toString(entity));
}
EntityUtils.consume(entity);
ret = true;
} catch (Exception e) {
LOG.error("Exception when sending http request to ali monitor", e);
} finally {
try {
if (response != null)
response.close();
httpClient.close();
} catch (Exception e) {
LOG.error("Exception when closing httpclient", e);
}
}
return ret;
}
代码示例来源:origin: gocd/gocd
@Test
public void shouldErrorOutIfServerRejectTheRequest() throws Exception {
final ArgumentCaptor<HttpRequestBase> argumentCaptor = ArgumentCaptor.forClass(HttpRequestBase.class);
final CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);
when(agentRegistry.uuid()).thenReturn("agent-uuid");
when(httpClient.execute(any(HttpRequestBase.class))).thenReturn(httpResponse);
when(httpResponse.getEntity()).thenReturn(new StringEntity("A token has already been issued for this agent."));
when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("https", 1, 2), SC_UNPROCESSABLE_ENTITY, null));
thrown.expect(RuntimeException.class);
thrown.expectMessage("A token has already been issued for this agent.");
tokenRequester.getToken();
}
代码示例来源:origin: stackoverflow.com
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
builder.build());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
sslsf).build();
HttpGet httpGet = new HttpGet("https://some-server");
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}
finally {
response.close();
}
代码示例来源:origin: igniterealtime/Openfire
private void handleHTTPError(CloseableHttpResponse response) throws RemoteException {
final StatusLine statusLine = response.getStatusLine();
final int status = statusLine.getStatusCode();
final String statusText = statusLine.getReasonPhrase();
final String body = response.getEntity().toString();
StringBuilder strBuf = new StringBuilder();
strBuf.append("Crowd returned HTTP error code:").append(status);
strBuf.append(" - ").append(statusText);
if (StringUtils.isNotBlank(body)) {
strBuf.append("\n").append(body);
}
throw new RemoteException(strBuf.toString());
}
代码示例来源:origin: openzipkin/brave
@Override protected void get(CloseableHttpClient client) throws Exception {
EntityUtils.consume(client.execute(new HttpGet(baseUrl())).getEntity());
}
代码示例来源:origin: gocd/gocd
private String responseBody(CloseableHttpResponse response) throws IOException {
try (InputStream is = response.getEntity() == null ? new NullInputStream(0) : response.getEntity().getContent()) {
return IOUtils.toString(is, StandardCharsets.UTF_8);
}
}
}
代码示例来源:origin: line/armeria
@Test
public void echoPostWithEmptyBody() throws Exception {
try (CloseableHttpClient hc = HttpClients.createMinimal()) {
final HttpPost post = new HttpPost(server().uri("/jsp/echo_post.jsp"));
try (CloseableHttpResponse res = hc.execute(post)) {
assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue())
.startsWith("text/html");
final String actualContent = CR_OR_LF.matcher(EntityUtils.toString(res.getEntity()))
.replaceAll("");
assertThat(actualContent).isEqualTo(
"<html><body>" +
"<p>Check request body</p>" +
"<p></p>" +
"</body></html>");
}
}
}
代码示例来源:origin: rubenlagus/TelegramBots
private String sendHttpPostRequest(HttpPost httppost) throws IOException {
try (CloseableHttpResponse response = httpClient.execute(httppost, options.getHttpContext())) {
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
return EntityUtils.toString(buf, StandardCharsets.UTF_8);
}
}
代码示例来源:origin: pentaho/pentaho-kettle
httpResponse = httpClient.execute( target, post, localContext );
} else {
httpResponse = httpClient.execute( post );
break;
default:
HttpEntity entity = httpResponse.getEntity();
if ( entity != null ) {
body = EntityUtils.toString( entity );
httpResponse.close();
代码示例来源:origin: gocd/gocd
@Test
public void shouldGetTokenFromServer() throws Exception {
final ArgumentCaptor<HttpRequestBase> argumentCaptor = ArgumentCaptor.forClass(HttpRequestBase.class);
final CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);
when(agentRegistry.uuid()).thenReturn("agent-uuid");
when(httpClient.execute(any(HttpRequestBase.class))).thenReturn(httpResponse);
when(httpResponse.getEntity()).thenReturn(new StringEntity("token-from-server"));
when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("https", 1, 2), SC_OK, null));
final String token = tokenRequester.getToken();
verify(httpClient).execute(argumentCaptor.capture());
final HttpRequestBase requestBase = argumentCaptor.getValue();
final List<NameValuePair> nameValuePairs = URLEncodedUtils.parse(requestBase.getURI(), StandardCharsets.UTF_8.name());
assertThat(token, is("token-from-server"));
assertThat(findParam(nameValuePairs, "uuid").getValue(), is("agent-uuid"));
}
代码示例来源:origin: alibaba/jstorm
private boolean httpGet(StringBuilder postAddr) {
boolean ret = false;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = null;
try {
HttpGet request = new HttpGet(postAddr.toString());
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
LOG.info(EntityUtils.toString(entity));
}
EntityUtils.consume(entity);
ret = true;
} catch (Exception e) {
LOG.error("Exception when sending http request to ali monitor", e);
} finally {
try {
if (response != null)
response.close();
httpClient.close();
} catch (Exception e) {
LOG.error("Exception when closing httpclient", e);
}
}
return ret;
}
代码示例来源:origin: apache/incubator-gobblin
private void processSingleRequestResponse(CloseableHttpResponse response) throws IOException,
UnexpectedResponseException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode < 400) {
return;
}
String entityStr = EntityUtils.toString(response.getEntity());
if (statusCode == 400
&& Operation.INSERT_ONLY_NOT_EXIST.equals(operation)
&& entityStr != null) { //Ignore if it's duplicate entry error code
JsonArray jsonArray = new JsonParser().parse(entityStr).getAsJsonArray();
JsonObject jsonObject = jsonArray.get(0).getAsJsonObject();
if (isDuplicate(jsonObject, statusCode)) {
return;
}
}
throw new RuntimeException("Failed due to " + entityStr + " (Detail: "
+ ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE) + " )");
}
代码示例来源:origin: gocd/gocd
protected synchronized boolean download(final DownloadableFile downloadableFile) throws Exception {
File toDownload = downloadableFile.getLocalFile();
LOG.info("Downloading {}", toDownload);
String url = downloadableFile.url(urlGenerator);
final HttpRequestBase request = new HttpGet(url);
request.setConfig(RequestConfig.custom().setConnectTimeout(HTTP_TIMEOUT_IN_MILLISECONDS).build());
try (CloseableHttpClient httpClient = httpClientBuilder.build();
CloseableHttpResponse response = httpClient.execute(request)) {
LOG.info("Got server response");
if (response.getEntity() == null) {
LOG.error("Unable to read file from the server response");
return false;
}
handleInvalidResponse(response, url);
try (BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(downloadableFile.getLocalFile()))) {
response.getEntity().writeTo(outStream);
LOG.info("Piped the stream to {}", downloadableFile);
}
}
return true;
}
内容来源于网络,如有侵权,请联系作者删除!