热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

org.apache.http.HttpEntity类的使用及代码示例

本文整理了Java中org.apache.http.HttpEntity类的一些代码示例,展示了HttpEntity类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Mav

本文整理了Java中org.apache.http.HttpEntity类的一些代码示例,展示了HttpEntity类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpEntity类的具体详情如下:
包路径:org.apache.http.HttpEntity
类名称:HttpEntity

HttpEntity介绍

[英]An entity that can be sent or received with an HTTP message. Entities can be found in some HttpEntityEnclosingRequest and in HttpResponse, where they are optional.

In some places, the JavaDoc distinguishes three kinds of entities, depending on where their #getContent originates:

  • streamed: The content is received from a stream, or generated on the fly. In particular, this category includes entities being received from a HttpConnection. #isStreaming entities are generally not #isRepeatable.
  • self-contained: The content is in memory or obtained by means that are independent from a connection or other entity. Self-contained entities are generally #isRepeatable.
  • wrapping: The content is obtained from another entity.
    This distinction is important for connection management with incoming entities. For entities that are created by an application and only sent using the HTTP components framework, the difference between streamed and self-contained is of little importance. In that case, it is suggested to consider non-repeatable entities as streamed, and those that are repeatable (without a huge effort) as self-contained.
    [中]可以通过HTTP消息发送或接收的实体。实体可以在一些HttpEntityEnclosingRequest和HttpResponse中找到,它们是可选的。
    在某些地方,JavaDoc根据其#getContent的来源区分三种实体:
    *流:内容从流接收或动态生成。特别是,此类别包括从HttpConnection接收的实体#isStreaming实体通常不可复制。
    *自包含:内容在内存中或通过独立于连接或其他实体的方式获得。自包含实体通常是可复制的。
    *包装:内容从另一个实体获取。
    这种区别对于传入实体的连接管理非常重要。对于由应用程序创建并仅使用HTTP组件框架发送的实体,流式和自包含式之间的区别并不重要。在这种情况下,建议考虑不可重复的实体流,以及那些可重复的(没有巨大的努力)作为自包含。

代码示例

代码示例来源:origin: apache/kylin

private String getContent(HttpResponse response) throws IOException {
StringBuffer result = new StringBuffer();
try (BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
}
return result.toString();
}

代码示例来源:origin: apache/geode

public HttpResponseAssert hasContentType(String contentType) {
assertThat(actual.getEntity().getContentType().getValue()).containsIgnoringCase(contentType);
return this;
}

代码示例来源:origin: stackoverflow.com

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urltofetch);
HttpResponse respOnse= httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
InputStream inputStream = entity.getContent();
// write the file to whether you want it.
}

代码示例来源:origin: robovm/robovm

public BufferedHttpEntity(final HttpEntity entity) throws IOException {
super(entity);
if (!entity.isRepeatable() || entity.getContentLength() <0) {
this.buffer = EntityUtils.toByteArray(entity);
} else {
this.buffer = null;
}
}

代码示例来源:origin: wiztools/rest-client

private static void appendHttpEntity(StringBuilder sb, HttpEntity e) {
try {
InputStream is = e.getContent();
String encoding = e.getContentEncoding().getValue();
System.out.println(encoding);
BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName(encoding)));
String str = null;
while ((str = br.readLine()) != null) {
sb.append(str);
}
br.close();
} catch (IOException ex) {
LOG.severe(ex.getMessage());
}
}

代码示例来源:origin: stackoverflow.com

HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
HttpGet httpget = new HttpGet("http://yoururl.com"); // Set the action you want to do
HttpResponse respOnse= httpclient.execute(httpget); // Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an InputStream with the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) // Read line by line
sb.append(line + "\n");
String resString = sb.toString(); // Result is here
is.close(); // Close the stream

代码示例来源:origin: ninjaframework/ninja

try {
HttpPost postRequest = new HttpPost(url);
postRequest.addHeader(header.getKey(), header.getValue());
postRequest.setEntity(entity);
respOnse= httpClient.execute(postRequest);
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
while ((output = br.readLine()) != null) {
sb.append(output);
if (br != null) {
try {
br.close();
} catch (IOException e) {
LOG.error("Failed to close resource", e);

代码示例来源:origin: opentripplanner/OpenTripPlanner

/** Get the AWS instance type if applicable */
public String getInstanceType () {
try {
HttpGet get = new HttpGet();
// see http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
// This seems very much not EC2-like to hardwire an IP address for getting instance metadata,
// but that's how it's done.
get.setURI(new URI("http://169.254.169.254/latest/meta-data/instance-type"));
get.setConfig(RequestConfig.custom()
.setConnectTimeout(2000)
.setSocketTimeout(2000)
.build()
);
HttpResponse res = httpClient.execute(get);
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String type = reader.readLine().trim();
reader.close();
return type;
} catch (Exception e) {
LOG.info("could not retrieve EC2 instance type, you may be running outside of EC2.");
return null;
}
}

代码示例来源:origin: medcl/elasticsearch-analysis-ik

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) {
buffer.add(line);
in.close();
response.close();
return buffer;

代码示例来源:origin: stackoverflow.com

DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(http://someJSONUrl/jsonWebService);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse respOnse= httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}

代码示例来源:origin: dreamhead/moco

@Override
public void run() throws IOException {
org.apache.http.HttpResponse httpRespOnse= helper.getResponse(remoteUrl("/dir/dir.response"));
String value = httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
assertThat(value, is("text/plain"));
String cOntent= CharStreams.toString(new InputStreamReader(httpResponse.getEntity().getContent()));
assertThat(content, is("response from dir"));
}
});

代码示例来源:origin: pentaho/pentaho-kettle

protected InputStreamReader openStream( String encoding, HttpResponse httpResponse ) throws Exception {
if ( !Utils.isEmpty( encoding ) ) {
return new InputStreamReader( httpResponse.getEntity().getContent(), encoding );
} else {
return new InputStreamReader( httpResponse.getEntity().getContent() );
}
}

代码示例来源:origin: robolectric/robolectric

@Test
public void testExecute() throws IOException {
AndroidHttpClient client = AndroidHttpClient.newInstance("foo");
FakeHttp.addPendingHttpResponse(200, "foo");
HttpResponse resp = client.execute(new HttpGet("/foo"));
assertThat(resp.getStatusLine().getStatusCode()).isEqualTo(200);
assertThat(CharStreams.toString(new InputStreamReader(resp.getEntity().getContent(), UTF_8)))
.isEqualTo("foo");
}
}

代码示例来源:origin: robolectric/robolectric

@Test
public void shouldReturnRequestsByRule_KeepsTrackOfOpenContentStreams() throws Exception {
TestHttpResponse testHttpRespOnse= new TestHttpResponse(200, "a cheery response body");
FakeHttp.addHttpResponseRule("http://some.uri", testHttpResponse);
assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed()).isTrue();
HttpResponse getRespOnse= requestDirector.execute(null, new HttpGet("http://some.uri"), null);
InputStream getRespOnseStream= getResponse.getEntity().getContent();
assertThat(CharStreams.toString(new InputStreamReader(getResponseStream, UTF_8)))
.isEqualTo("a cheery response body");
assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed()).isFalse();
HttpResponse postRespOnse=
requestDirector.execute(null, new HttpPost("http://some.uri"), null);
InputStream postRespOnseStream= postResponse.getEntity().getContent();
assertThat(CharStreams.toString(new InputStreamReader(postResponseStream, UTF_8)))
.isEqualTo("a cheery response body");
assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed()).isFalse();
getResponseStream.close();
assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed()).isFalse();
postResponseStream.close();
assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed()).isTrue();
}

代码示例来源:origin: neo4j/neo4j

@Test
public void shouldParameteriseUrisInRelationshipRepresentationWithoutHostHeaderUsingRequestUri() throws Exception
{
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( getServerUri() + "db/data/relationship/" + likes );
httpget.setHeader( "Accept", "application/json" );
HttpResponse respOnse= httpclient.execute( httpget );
HttpEntity entity = response.getEntity();
String entityBody = IOUtils.toString( entity.getContent(), StandardCharsets.UTF_8 );
assertThat( entityBody, containsString( getServerUri() + "db/data/relationship/" + likes ) );
}
finally
{
httpclient.getConnectionManager().shutdown();
}
}

代码示例来源:origin: apache/nifi

private JSONObject readJSONObjectFromUrlPOST(String urlString, Map headers, String payload) throws IOException, JSONException {
HttpClient httpClient = openConnection();
HttpPost request = new HttpPost(urlString);
for (Map.Entry entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
HttpEntity httpEntity = new StringEntity(payload);
request.setEntity(httpEntity);
HttpResponse respOnse= httpClient.execute(request);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " : " + response.getStatusLine().getReasonPhrase());
}
InputStream cOntent= response.getEntity().getContent();
return readAllIntoJSONObject(content);
}

代码示例来源:origin: alibaba/nacos

public static HttpResult httpPostLarge(String url, Map headers, String content) {
try {
HttpClientBuilder builder = HttpClients.custom();
builder.setUserAgent(UtilsAndCommons.SERVER_VERSION);
builder.setConnectionTimeToLive(500, TimeUnit.MILLISECONDS);
CloseableHttpClient httpClient = builder.build();
HttpPost httpost = new HttpPost(url);
for (Map.Entry entry : headers.entrySet()) {
httpost.setHeader(entry.getKey(), entry.getValue());
}
httpost.setEntity(new StringEntity(content, ContentType.create("application/json", "UTF-8")));
HttpResponse respOnse= httpClient.execute(httpost);
HttpEntity entity = response.getEntity();
HeaderElement[] headerElements = entity.getContentType().getElements();
String charset = headerElements[0].getParameterByName("charset").getValue();
return new HttpResult(response.getStatusLine().getStatusCode(),
IOUtils.toString(entity.getContent(), charset), Collections.emptyMap());
} catch (Exception e) {
return new HttpResult(500, e.toString(), Collections.emptyMap());
}
}

代码示例来源:origin: stackoverflow.com

HttpHost proxy = new HttpHost("ip address",port number);
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
HttpPost httpost = new HttpPost(url);
List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("param name", param));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1));
HttpResponse respOnse= httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
System.out.println("Request Handled?: " + response.getStatusLine());
InputStream in = entity.getContent();
httpclient.getConnectionManager().shutdown();

代码示例来源:origin: alibaba/nacos

public static HttpResult httpPost(String url, List headers, Map paramValues, String encoding) {
try {
HttpPost httpost = new HttpPost(url);
RequestConfig requestCOnfig= RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000).setSocketTimeout(5000).setRedirectsEnabled(true).setMaxRedirects(5).build();
httpost.setConfig(requestConfig);
List nvps = new ArrayList();
for (Map.Entry entry : paramValues.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
HttpResponse respOnse= postClient.execute(httpost);
HttpEntity entity = response.getEntity();
String charset = encoding;
if (entity.getContentType() != null) {
HeaderElement[] headerElements = entity.getContentType().getElements();
if (headerElements != null && headerElements.length > 0 && headerElements[0] != null &&
headerElements[0].getParameterByName("charset") != null) {
charset = headerElements[0].getParameterByName("charset").getValue();
}
}
return new HttpResult(response.getStatusLine().getStatusCode(), IOUtils.toString(entity.getContent(), charset), Collections.emptyMap());
} catch (Throwable e) {
return new HttpResult(500, e.toString(), Collections.emptyMap());
}
}

代码示例来源:origin: stackoverflow.com

HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/");
// Request parameters and other properties.
List params = new ArrayList(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse respOnse= httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
// do something useful
} finally {
instream.close();
}
}

推荐阅读
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • http:my.oschina.netleejun2005blog136820刚看到群里又有同学在说HTTP协议下的Get请求参数长度是有大小限制的,最大不能超过XX ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 在重复造轮子的情况下用ProxyServlet反向代理来减少工作量
    像不少公司内部不同团队都会自己研发自己工具产品,当各个产品逐渐成熟,到达了一定的发展瓶颈,同时每个产品都有着自己的入口,用户 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • FeatureRequestIsyourfeaturerequestrelatedtoaproblem?Please ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
  • sklearn数据集库中的常用数据集类型介绍
    本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Google Play推出全新的应用内评价API,帮助开发者获取更多优质用户反馈。用户每天在Google Play上发表数百万条评论,这有助于开发者了解用户喜好和改进需求。开发者可以选择在适当的时间请求用户撰写评论,以获得全面而有用的反馈。全新应用内评价功能让用户无需返回应用详情页面即可发表评论,提升用户体验。 ... [详细]
author-avatar
子华2502924833
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有