本文整理汇总了Java中org.apache.http.HttpEntity类的典型用法代码示例。如果您正苦于以下问题:Java HttpEntity类的具体用法?Java HttpEntity怎么用?Java HttpEntity使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpEntity类属于org.apache.http包,在下文中一共展示了HttpEntity类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getRedirect
import org.apache.http.HttpEntity; //导入依赖的package包/类
/**
* get a redirect for an url: this method shall be called if it is expected that a url
* is redirected to another url. This method then discovers the redirect.
* @param urlstring
* @param useAuthentication
* @return the redirect url for the given urlstring
* @throws IOException if the url is not redirected
*/
public static String getRedirect(String urlstring) throws IOException {
HttpGet get = new HttpGet(urlstring);
get.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
get.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
CloseableHttpClient httpClient = getClosableHttpClient();
HttpResponse httpResponse = httpClient.execute(get);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
if (httpResponse.getStatusLine().getStatusCode() == 301) {
for (Header header: httpResponse.getAllHeaders()) {
if (header.getName().equalsIgnoreCase("location")) {
EntityUtils.consumeQuietly(httpEntity);
return header.getValue();
}
}
EntityUtils.consumeQuietly(httpEntity);
throw new IOException("redirect for " + urlstring+ ": no location attribute found");
} else {
EntityUtils.consumeQuietly(httpEntity);
throw new IOException("no redirect for " + urlstring+ " fail: " + httpResponse.getStatusLine().getStatusCode() + ": " + httpResponse.getStatusLine().getReasonPhrase());
}
} else {
throw new IOException("client connection to " + urlstring + " fail: no connection");
}
}
示例2: getRequest
import org.apache.http.HttpEntity; //导入依赖的package包/类
/**
* {@inheritDoc}
*/
@Override
public HttpRequestBase getRequest(SipProfile acc) throws IOException {
String requestURL = "https://samurai.sipgate.net/RPC2";
HttpPost httpPost = new HttpPost(requestURL);
// TODO : this is wrong ... we should use acc user/password instead of SIP ones, but we don't have it
String userpassword = acc.username + ":" + acc.data;
String encodedAuthorization = Base64.encodeBytes( userpassword.getBytes() );
httpPost.addHeader("Authorization", "Basic " + encodedAuthorization);
httpPost.addHeader("Content-Type", "text/xml");
// prepare POST body
String body = "<?xml version='1.0'?><methodCall><methodName>samurai.BalanceGet</methodName></methodCall>";
// set POST body
HttpEntity entity = new StringEntity(body);
httpPost.setEntity(entity);
return httpPost;
}
示例3: postRecommendationReaction
import org.apache.http.HttpEntity; //导入依赖的package包/类
public static boolean postRecommendationReaction(@NotNull String lessonId, @NotNull String user, int reaction) {
final HttpPost post = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.RECOMMENDATION_REACTIONS_URL);
final String json = new Gson()
.toJson(new StepicWrappers.RecommendationReactionWrapper(new StepicWrappers.RecommendationReaction(reaction, user, lessonId)));
post.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
if (client == null) return false;
setTimeout(post);
try {
final CloseableHttpResponse execute = client.execute(post);
final int statusCode = execute.getStatusLine().getStatusCode();
final HttpEntity entity = execute.getEntity();
final String entityString = EntityUtils.toString(entity);
EntityUtils.consume(entity);
if (statusCode == HttpStatus.SC_CREATED) {
return true;
}
else {
LOG.warn("Stepic returned non-201 status code: " + statusCode + " " + entityString);
return false;
}
}
catch (IOException e) {
LOG.warn(e.getMessage());
return false;
}
}
示例4: getRequest
import org.apache.http.HttpEntity; //导入依赖的package包/类
@Override
public HttpRequestBase getRequest(SipProfile acc) throws IOException {
String requestURL = "http://200.152.124.172/billing/webservice/Server.php";
HttpPost httpPost = new HttpPost(requestURL);
httpPost.addHeader("SOAPAction", "\"mostra_creditos\"");
httpPost.addHeader("Content-Type", "text/xml");
// prepare POST body
String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope " +
"SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
"xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
"xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" " +
"xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"" +
"><SOAP-ENV:Body><mostra_creditos SOAP-ENC:root=\"1\">" +
"<chave xsi:type=\"xsd:string\">" +
acc.data +
"</chave><username xsi:type=\"xsd:string\">" +
acc.username.replaceAll("^12", "") +
"</username></mostra_creditos></SOAP-ENV:Body></SOAP-ENV:Envelope>";
Log.d(THIS_FILE, "Sending request for user " + acc.username.replaceAll("^12", ""));
// set POST body
HttpEntity entity = new StringEntity(body);
httpPost.setEntity(entity);
return httpPost;
}
示例5: getContentCharSet
import org.apache.http.HttpEntity; //导入依赖的package包/类
/**
* Obtains character set of the entity, if known.
*
* @param entity must not be null
* @return the character set, or null if not found
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null
*
* @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)}
*/
@Deprecated
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}
return charset;
}
示例6: doDownload
import org.apache.http.HttpEntity; //导入依赖的package包/类
/**
* 通过httpClient get 下载文件
*
* @param url 网络文件全路径
* @param savePath 保存文件全路径
* @return 状态码 200表示成功
*/
public static int doDownload(String url, String savePath) {
// 创建默认的HttpClient实例.
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
CloseableHttpResponse closeableHttpResponse = null;
try {
closeableHttpResponse = closeableHttpClient.execute(get);
HttpEntity entity = closeableHttpResponse.getEntity();
if (entity != null) {
InputStream in = entity.getContent();
FileOutputStream out = new FileOutputStream(savePath);
IOUtils.copy(in, out);
EntityUtils.consume(entity);
closeableHttpResponse.close();
}
int code = closeableHttpResponse.getStatusLine().getStatusCode();
closeableHttpClient.close();
return code;
} catch (IOException e) {
e.printStackTrace();
} finally {
closeSource(closeableHttpClient, closeableHttpResponse);
}
return 0;
}
示例7: useHttpClientPost
import org.apache.http.HttpEntity; //导入依赖的package包/类
private void useHttpClientPost(String url) {
HttpPost mHttpPost = new HttpPost(url);
mHttpPost.addHeader("Connection", "Keep-Alive");
try {
HttpClient mHttpClient = createHttpClient();
List<NameValuePair> postParams = new ArrayList<>();
//要传递的参数
postParams.add(new BasicNameValuePair("ip", "59.108.54.37"));
mHttpPost.setEntity(new UrlEncodedFormEntity(postParams));
HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
HttpEntity mHttpEntity = mHttpResponse.getEntity();
int code = mHttpResponse.getStatusLine().getStatusCode();
if (null != mHttpEntity) {
InputStream mInputStream = mHttpEntity.getContent();
String respose = converStreamToString(mInputStream);
Log.d(TAG, "请求状态码:" + code + "\n请求结果:\n" + respose);
mInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
示例8: deployApp
import org.apache.http.HttpEntity; //导入依赖的package包/类
/**
* Sets the app to active state
*
* @param customerName
* the name of the customer
* @param appName
* the name of the app
* @return request object to check status codes and return values
*/
public Response deployApp( String customerName, String appName )
{
HttpPut request = new HttpPut( this.yambasBase + "customers/" + customerName + "/apps/" + appName );
setAuthorizationHeader( request );
request.addHeader( "ContentType", "application/json" );
request.addHeader( "x-apiomat-system", this.system.toString( ) );
try
{
final HttpEntity requestEntity = new StringEntity(
"{\"applicationStatus\":{\"" + this.system + "\":\"ACTIVE\"}, \"applicationName\":\"" +
appName + "\"}",
ContentType.APPLICATION_JSON );
request.setEntity( requestEntity );
final HttpResponse response = this.client.execute( request );
return new Response( response );
}
catch ( final IOException e )
{
e.printStackTrace( );
}
return null;
}
示例9: process
import org.apache.http.HttpEntity; //导入依赖的package包/类
@Override
public void process(final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
final HttpRequestAttachment.Builder builder = create("Request", request.getRequestLine().getUri())
.withMethod(request.getRequestLine().getMethod());
Stream.of(request.getAllHeaders())
.forEach(header -> builder.withHeader(header.getName(), header.getValue()));
if (request instanceof HttpEntityEnclosingRequest) {
final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
final ByteArrayOutputStream os = new ByteArrayOutputStream();
entity.writeTo(os);
final String body = new String(os.toByteArray(), StandardCharsets.UTF_8);
builder.withBody(body);
}
final HttpRequestAttachment requestAttachment = builder.build();
processor.addAttachment(requestAttachment, renderer);
}
示例10: extractFromResponse
import org.apache.http.HttpEntity; //导入依赖的package包/类
private RestHeartClientResponse extractFromResponse(final CloseableHttpResponse httpResponse) {
RestHeartClientResponse response = null;
JsonObject responseObj = null;
if (httpResponse != null) {
StatusLine statusLine = httpResponse.getStatusLine();
Header[] allHeaders = httpResponse.getAllHeaders();
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
try {
String responseStr = IOUtils.toString(resEntity.getContent(), "UTF-8");
if (responseStr != null && !responseStr.isEmpty()) {
JsonParser parser = new JsonParser();
responseObj = parser.parse(responseStr).getAsJsonObject();
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Was unable to extract response body", e);
}
}
response = new RestHeartClientResponse(statusLine, allHeaders, responseObj);
}
return response;
}
示例11: Request
import org.apache.http.HttpEntity; //导入依赖的package包/类
public Request(String id,
String method,
String url,
ResponseType responseType,
Map<String, String> headers,
Map<String, String> parameters,
HttpEntity entity,
Map<String, String> extras) {
this.id = StringUtils.isNotBlank(id) ? id : SpiderStrUtils.getUUID();
this.method = StringUtils.isNotBlank(method) ? method : Request.METHOD_GET;
this.url = url;
this.responseType = responseType != null ? responseType : ResponseType.TEXT;
this.headers = headers;
this.parameters = parameters;
this.entity = entity;
this.extras = extras;
}
示例12: parseResponse
import org.apache.http.HttpEntity; //导入依赖的package包/类
@Override
public ReadAggregateGroupResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
int status = response.getStatusLine().getStatusCode();
switch (status) {
case 200:
HttpEntity entity = response.getEntity();
StringWriter writer = new StringWriter();
IOUtils.copy(entity.getContent(), writer, "UTF-8");
String json = writer.toString();
return mapper.readValue(json, ReadAggregateGroupResult.class);
case 400:
throw new MalformedEventException();
case 401:
throw new UnauthorizedAccessException();
default:
throw new UnknownAPIException(response.getStatusLine().toString());
}
}
示例13: parseResponse
import org.apache.http.HttpEntity; //导入依赖的package包/类
@Override
public PyroclastConsumer parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
int status = response.getStatusLine().getStatusCode();
switch (status) {
case 200:
HttpEntity entity = response.getEntity();
StringWriter writer = new StringWriter();
IOUtils.copy(entity.getContent(), writer, "UTF-8");
String json = writer.toString();
SubscribeToTopicResult result = mapper.readValue(json, SubscribeToTopicResult.class);
if (result.getSuccess()) {
return new PyroclastConsumer(topicId, readApiKey, format, endpoint, subscriptionName);
} else {
throw new UnknownAPIException(result.getFailureReason());
}
case 401:
throw new UnauthorizedAccessException();
default:
throw new UnknownAPIException(response.getStatusLine().toString());
}
}
示例14: updateConfig
import org.apache.http.HttpEntity; //导入依赖的package包/类
/**
* Updates a modules config for the given app
*
* @param customerName
* the name of the customer
* @param appName
* the name of the app
* @param moduleName
* the name of the module to update config for
* @param key
* config key
* @param value
* value of the config
* @return request object to check status codes and return values
*/
public Response updateConfig( String customerName, String appName, String moduleName, String key,
String value )
{
final HttpPut request = new HttpPut( this.yambasBase + "customers/" + customerName + "/apps/" + appName );
setAuthorizationHeader( request );
request.addHeader( "ContentType", "application/json" );
request.addHeader( "x-apiomat-system", this.system.toString( ) );
try
{
final HttpEntity requestEntity = new StringEntity(
"{\"configuration\":" + " {\"" + this.system.toString( ).toLowerCase( ) + "Config\": {\"" +
moduleName + "\":{\"" + key + "\":\"" + value + "\"}}}, \"applicationName\":\"" + appName + "\"}",
ContentType.APPLICATION_JSON );
request.setEntity( requestEntity );
final HttpResponse response = this.client.execute( request );
return new Response( response );
}
catch ( final IOException e )
{
e.printStackTrace( );
}
return null;
}
示例15: createIndex
import org.apache.http.HttpEntity; //导入依赖的package包/类
private void createIndex() {
Response response;
try (InputStream payload = FactSearchManager.class.getClassLoader().getResourceAsStream(MAPPINGS_JSON)) {
// Need to use low-level client here because the Index API is not yet supported by the high-level client.
HttpEntity body = new InputStreamEntity(payload, ContentType.APPLICATION_JSON);
response = clientFactory.getLowLevelClient().performRequest("PUT", INDEX_NAME, Collections.emptyMap(), body);
} catch (IOException ex) {
throw logAndExit(ex, "Could not perform request to create index.");
}
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
String msg = String.format("Could not create index '%s'.", INDEX_NAME);
LOGGER.error(msg);
throw new IllegalStateException(msg);
}
LOGGER.info("Successfully created index '%s'.", INDEX_NAME);
}