本文整理汇总了Java中org.apache.http.HttpEntity.getContent方法的典型用法代码示例。如果您正苦于以下问题:Java HttpEntity.getContent方法的具体用法?Java HttpEntity.getContent怎么用?Java HttpEntity.getContent使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.http.HttpEntity
的用法示例。
在下文中一共展示了HttpEntity.getContent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: httpPush
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
private static String httpPush (ArrayList<NameValuePair> nameValuePairs,String action) throws Exception {
HttpPost httppost = new HttpPost(FLOWZR_API_URL + nsString + "/" + action + "/");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
HttpResponse response;
String strResponse;
response = http_client.execute(httppost);
HttpEntity entity = response.getEntity();
int code = response.getStatusLine().getStatusCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
strResponse = reader.readLine();
entity.consumeContent();
if (code!=200) {
throw new Exception(Html.fromHtml(strResponse).toString());
}
return strResponse;
}
示例2: getResponseString
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
/**
* Extracts the response string from the given HttpEntity.
*
* @param entity HttpEntity that contains the response
* @return response String
*/
public static String getResponseString(HttpEntity entity) {
StringBuilder builder = new StringBuilder();
if (entity != null) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
builder.append(inputLine);
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
return null;
}
}
return builder.toString();
}
示例3: oauth
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
/**
* Perform an Oauth2 callback to the Discord servers with the token given by the user's approval
* @param token Token from user
* @param res Passed on response
* @throws ClientProtocolException Error in HTTP protocol
* @throws IOException Encoding exception or error in protocol
* @throws NoAPIKeyException No API keys set
*/
static void oauth(String token, Response res) throws ClientProtocolException, IOException, NoAPIKeyException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost("https://discordapp.com/api/oauth2/token");
List<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("client_id", Bot.getInstance().getApiKeys().get("dashboardid")));
nvp.add(new BasicNameValuePair("client_secret", Bot.getInstance().getApiKeys().get("dashboardsecret")));
nvp.add(new BasicNameValuePair("grant_type", "authorization_code"));
nvp.add(new BasicNameValuePair("code", token));
post.setEntity(new UrlEncodedFormEntity(nvp));
String accessToken;
CloseableHttpResponse response = httpclient.execute(post);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
JsonObject authJson;
try(BufferedReader buffer = new BufferedReader(new InputStreamReader(entity.getContent()))) {
authJson = Json.parse(buffer.lines().collect(Collectors.joining("\n"))).asObject();
}
accessToken = authJson.getString("access_token", "");
EntityUtils.consume(entity);
getGuilds(res, accessToken);
} finally {
response.close();
}
}
示例4: closeResponse
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
/**
* 关闭response
* @param response
*/
private void closeResponse(HttpResponse response) {
if(response!=null){
try {
HttpEntity entity = response.getEntity();
if(entity!=null){
InputStream in = entity.getContent();
if(in!=null){
in.close();
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
// if(response instanceof Closeable){
// try {
// ((Closeable)response).close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}
}
示例5: downloadExifTools
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
private static void downloadExifTools(String exifToolsUrl, HttpClient httpClient, FileSystem fileSystem) throws IOException {
HttpGet request = new HttpGet(exifToolsUrl);
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
// Download the zip file
File tmpFile = fileSystem.getPath(tmpFilename).toFile();
tmpFile.delete(); // Delete the tmp file in case it already exists
try (InputStream inputStream = entity.getContent();
OutputStream outputStream = new FileOutputStream(tmpFile)) {
IOUtils.copy(inputStream, outputStream);
}
// Unzip
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(tmpFile))) {
ZipEntry ze = zis.getNextEntry();
if (ze != null) {
File newFile = fileSystem.getPath(targetFilename).toFile();
newFile.delete(); // Delete in case it already exists
byte[] buffer = new byte[4096];
try (FileOutputStream fos = new FileOutputStream(newFile)) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
}
}
// Delete .zipFile
tmpFile.delete();
}
}
示例6: postWithRedirect
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
public static void postWithRedirect(KeycloakSession session, String url, HttpEntity postBody) throws IOException {
HttpClient httpClient = session.getProvider(HttpClientProvider.class).getHttpClient();
for (int i = 0; i < 2; i++) { // follow redirects once
HttpPost post = new HttpPost(url);
post.setEntity(postBody);
HttpResponse response = httpClient.execute(post);
try {
int status = response.getStatusLine().getStatusCode();
if (status == 302 && !url.endsWith("/")) {
String redirect = response.getFirstHeader(HttpHeaders.LOCATION).getValue();
String withSlash = url + "/";
if (withSlash.equals(redirect)) {
url = withSlash;
continue;
}
}
} finally {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
if (is != null)
is.close();
}
}
break;
}
}
示例7: getResponseData
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
byte[] getResponseData(HttpEntity entity) throws IOException {
byte[] responseBody = null;
if (entity != null) {
InputStream instream = entity.getContent();
if (instream != null) {
long contentLength = entity.getContentLength();
if (contentLength > 2147483647L) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in " +
"memory");
}
if (contentLength < 0) {
contentLength = PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM;
}
try {
ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
byte[] tmp = new byte[4096];
while (true) {
int l = instream.read(tmp);
if (l == -1 || Thread.currentThread().isInterrupted()) {
break;
}
buffer.append(tmp, 0, l);
sendProgressDataMessage(copyOfRange(tmp, 0, l));
sendProgressMessage((long) 0, contentLength);
}
AsyncHttpClient.silentCloseInputStream(instream);
responseBody = buffer.toByteArray();
} catch (OutOfMemoryError e) {
System.gc();
throw new IOException("File too large to fit into available memory");
} catch (Throwable th) {
AsyncHttpClient.silentCloseInputStream(instream);
}
}
}
return responseBody;
}
示例8: entityToBytes
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
PoolingByteArrayOutputStream bytes =
new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
byte[] buffer = null;
try {
InputStream in = entity.getContent();
if (in == null) {
throw new ServerError();
}
buffer = mPool.getBuf(1024);
int count;
while ((count = in.read(buffer)) != -1) {
bytes.write(buffer, 0, count);
}
return bytes.toByteArray();
} finally {
try {
// Close the InputStream and release the resources by "consuming the content".
entity.consumeContent();
} catch (IOException e) {
// This can happen if there was an exception above that left the entity in
// an invalid state.
VolleyLog.v("Error occured when calling consumingContent");
}
mPool.returnBuf(buffer);
bytes.close();
}
}
示例9: proxyRequest
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
Response proxyRequest(String method, ContainerRequestContext ctx) {
if (!Config.getConfigBoolean("es.proxy_enabled", false)) {
return Response.status(Response.Status.FORBIDDEN.getStatusCode(), "This feature is disabled.").build();
}
String appid = ParaObjectUtils.getAppidFromAuthHeader(ctx.getHeaders().getFirst(HttpHeaders.AUTHORIZATION));
String path = getCleanPath(getPath(ctx));
if (StringUtils.isBlank(appid)) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
try {
if ("reindex".equals(path) && POST.equals(method)) {
return handleReindexTask(appid);
}
Header[] headers = getHeaders(ctx.getHeaders());
HttpEntity resp;
RestClient client = getClient(appid);
if (client != null) {
if (ctx.getEntityStream() != null && ctx.getEntityStream().available() > 0) {
HttpEntity body = new InputStreamEntity(ctx.getEntityStream(), ContentType.APPLICATION_JSON);
resp = client.performRequest(method, path, Collections.emptyMap(), body, headers).getEntity();
} else {
resp = client.performRequest(method, path, headers).getEntity();
}
if (resp != null && resp.getContent() != null) {
Header type = resp.getContentType();
Object response = getTransformedResponse(appid, resp.getContent(), ctx);
return Response.ok(response).header(type.getName(), type.getValue()).build();
}
}
} catch (Exception ex) {
logger.warn("Failed to proxy '{} {}' to Elasticsearch: {}", method, path, ex.getMessage());
}
return Response.status(Response.Status.BAD_REQUEST).build();
}
示例10: getResponseData
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
/**
* Returns byte array of response HttpEntity contents
*
* @param entity can be null
* @return response entity body or null
* @throws java.io.IOException if reading entity or creating byte array failed
*/
@Override
byte[] getResponseData(HttpEntity entity) throws IOException {
byte[] responseBody = null;
if (entity != null) {
InputStream instream = entity.getContent();
if (instream != null) {
long contentLength = entity.getContentLength();
if (contentLength > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
if (contentLength < 0) {
contentLength = BUFFER_SIZE;
}
try {
ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
try {
byte[] tmp = new byte[BUFFER_SIZE];
int l;
// do not send messages if request has been cancelled
while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
buffer.append(tmp, 0, l);
sendProgressDataMessage(copyOfRange(tmp, 0, l));
}
} finally {
AsyncHttpClient.silentCloseInputStream(instream);
}
responseBody = buffer.toByteArray();
} catch (OutOfMemoryError e) {
System.gc();
throw new IOException("File too large to fit into available memory");
}
}
}
return responseBody;
}
示例11: toString
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
/**
* Get the entity content as a String, using the provided default character set
* if none is found in the entity.
* If defaultCharset is null, the default "ISO-8859-1" is used.
*
* @param entity must not be null
* @param defaultCharset character set to be applied if none found in the entity
* @return the entity content as a String. May be null if
* {@link HttpEntity#getContent()} is null.
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
* @throws IOException if an error occurs reading the input stream
*/
public static String toString(
final HttpEntity entity, final Charset defaultCharset) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
ContentType contentType = ContentType.getOrDefault(entity);
Charset charset = contentType.getCharset();
if (charset == null) {
charset = defaultCharset;
}
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
instream.close();
}
}
示例12: makeHttpRequest
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
@Override
protected HttpResponse makeHttpRequest(HttpEntity entity, long startTime) {
if (entity != null) {
requestBuilder.setEntity(entity);
requestBuilder.setHeader(entity.getContentType());
}
HttpUriRequest httpRequest = requestBuilder.build();
CloseableHttpClient client = clientBuilder.build();
BasicHttpContext context = new BasicHttpContext();
context.setAttribute(URI_CONTEXT_KEY, getRequestUri());
CloseableHttpResponse httpResponse;
byte[] bytes;
try {
httpResponse = client.execute(httpRequest, context);
HttpEntity responseEntity = httpResponse.getEntity();
if (responseEntity == null || responseEntity.getContent() == null) {
bytes = new byte[0];
} else {
InputStream is = responseEntity.getContent();
bytes = FileUtils.toBytes(is);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
long responseTime = getResponseTime(startTime);
HttpResponse response = new HttpResponse(responseTime);
response.setUri(getRequestUri());
response.setBody(bytes);
response.setStatus(httpResponse.getStatusLine().getStatusCode());
for (Cookie c : cookieStore.getCookies()) {
com.intuit.karate.http.Cookie cookie = new com.intuit.karate.http.Cookie(c.getName(), c.getValue());
cookie.put(DOMAIN, c.getDomain());
cookie.put(PATH, c.getPath());
if (c.getExpiryDate() != null) {
cookie.put(EXPIRES, c.getExpiryDate().getTime() + "");
}
cookie.put(PERSISTENT, c.isPersistent() + "");
cookie.put(SECURE, c.isSecure() + "");
response.addCookie(cookie);
}
cookieStore.clear(); // we rely on the StepDefs for cookie 'persistence'
for (Header header : httpResponse.getAllHeaders()) {
response.addHeader(header.getName(), header.getValue());
}
return response;
}
示例13: getResponseData
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
/**
* Returns byte array of response HttpEntity contents
*
* @param entity can be null
* @return response entity body or null
* @throws IOException if reading entity or creating byte array failed
*/
@Override
byte[] getResponseData(HttpEntity entity) throws IOException {
byte[] responseBody = null;
if (entity != null) {
InputStream instream = entity.getContent();
if (instream != null) {
long contentLength = entity.getContentLength();
if (contentLength > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
if (contentLength < 0) {
contentLength = BUFFER_SIZE;
}
try {
ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
try {
byte[] tmp = new byte[BUFFER_SIZE];
int l;
// do not send messages if request has been cancelled
while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
buffer.append(tmp, 0, l);
sendProgressDataMessage(copyOfRange(tmp, 0, l));
}
} finally {
AsyncHttpClient.silentCloseInputStream(instream);
}
responseBody = buffer.toByteArray();
} catch (OutOfMemoryError e) {
System.gc();
throw new IOException("File too large to fit into available memory");
}
}
}
return responseBody;
}
示例14: toByteArray
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
/**
* read contents from an entity, with a specified maximum.
* @param entity The entity from which to read
* @param maxBytes The maximum number of bytes to read
* @return A byte array containing maxBytes or fewer bytes read from the entity
*
* @throws IOException thrown when reading fails for any reason
*/
protected byte[] toByteArray(HttpEntity entity, int maxBytes) throws IOException {
if (entity == null) {
return new byte[0];
}
InputStream is = entity.getContent();
int size = (int) entity.getContentLength();
if (size <= 0 || size > maxBytes) {
size = maxBytes;
}
int actualSize = 0;
byte[] buf = new byte[size];
while (actualSize < size) {
int remain = size - actualSize;
int readBytes = is.read(buf, actualSize, Math.min(remain, 1500));
if (readBytes <= 0) {
break;
}
actualSize += readBytes;
}
int ch = is.read();
if (ch >= 0) {
truncated = true;
}
if (actualSize == buf.length) {
return buf;
}
return Arrays.copyOfRange(buf, 0, actualSize);
}
示例15: doPost
import org.apache.http.HttpEntity; //导入方法依赖的package包/类
public String doPost(String url,List <NameValuePair> nvps,BasicCookieStore loginStatus) throws Exception{
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(loginStatus).build();
String webStr = "";
try {
//1Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);//设置超时配置
/*
* nvps 内容
* List <NameValuePair> nvps = new ArrayList <NameValuePair>();
* //网页post参数 http://www.scnj.tv/appqy_api/api.php?api_key=AaPpQqYyCcOoMmLl&opt=getCategory
* nvps.add(new BasicNameValuePair("api_key", WEB_KEY));
* nvps.add(new BasicNameValuePair("opt", "login"));
* nvps.add(new BasicNameValuePair("uid", uid));
* nvps.add(new BasicNameValuePair("pass", password));
* */
httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));//需加上UTF8 不然提交出去到网站会变成乱码 TODO 以后需要提取配置编码
CloseableHttpResponse response2;
//2发送请求
response2 = httpclient.execute(httpPost);
System.out.println(response2.getStatusLine());
//3处理响应结果
if (response2.getStatusLine().getStatusCode() == 200) {
//4从输入流读取网页字符串内容
HttpEntity entity2 = response2.getEntity();
InputStream in = entity2.getContent();
webStr = readResponse(in);
//log.debug("网络请求接收到的返回数据"+webStr);
EntityUtils.consume(entity2);
}
// and ensure it is fully consumed
response2.close();
}catch(java.io.IOException e){
e.getStackTrace();
log.error("Web服务器端网络异常!info:"+e.getStackTrace().toString());
}
finally {
//始终保持执行
httpclient.close();
}
return webStr;
}