本文整理汇总了Java中org.apache.http.entity.ContentType类的典型用法代码示例。如果您正苦于以下问题:Java ContentType类的具体用法?Java ContentType怎么用?Java ContentType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ContentType类属于org.apache.http.entity包,在下文中一共展示了ContentType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: callGistApi
import org.apache.http.entity.ContentType; //导入依赖的package包/类
/**
* Call the API to create gist and return the http url if any
*/
private String callGistApi(String gistJson, GistListener listener) {
try {
CloseableHttpClient httpclient = createDefault();
HttpPost httpPost = new HttpPost(GIST_API);
httpPost.setHeader("Accept", "application/vnd.github.v3+json");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setEntity(new StringEntity(gistJson, ContentType.APPLICATION_JSON));
CloseableHttpResponse response = httpclient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
JsonObject result = (JsonObject) new JsonParser().parse(EntityUtils.toString(responseEntity));
EntityUtils.consume(responseEntity);
response.close();
httpclient.close();
return result.getAsJsonPrimitive("html_url").getAsString();
} catch (Exception ex) {
}
return null;
}
示例2: authClient
import org.apache.http.entity.ContentType; //导入依赖的package包/类
public static String authClient() {
CloseableHttpClient httpClient = buildHttpClient();
HttpPost httpPost = new HttpPost(UrlConfig.authClient);
httpPost.addHeader(CookieManager.cookieHeader());
String param = Optional.ofNullable(ResultManager.get("tk")).map(r -> null == r.getValue() ? StringUtils.EMPTY : r.getValue().toString()).orElse(StringUtils.EMPTY);
httpPost.setEntity(new StringEntity("tk=" + param, ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));
String result = StringUtils.EMPTY;
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
result = EntityUtils.toString(response.getEntity());
CookieManager.touch(response);
} catch (IOException e) {
logger.error("authClient error", e);
}
return result;
}
示例3: testProtectedResourceAnonymousMeans403
import org.apache.http.entity.ContentType; //导入依赖的package包/类
/**
* No username provided gives 403
*/
@Test
public void testProtectedResourceAnonymousMeans403() throws IOException {
final HttpPost message = new HttpPost(BASE_URI + RESOURCE);
message.setEntity(new StringEntity("{\"id\":0}", ContentType.APPLICATION_JSON));
final HttpResponse response = httpclient.execute(message);
try {
Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusLine().getStatusCode());
} finally {
IOUtils.closeQuietly(response.getEntity().getContent());
}
}
示例4: clearScrollEntity
import org.apache.http.entity.ContentType; //导入依赖的package包/类
static HttpEntity clearScrollEntity(String scroll) {
try (XContentBuilder entity = JsonXContent.contentBuilder()) {
return new StringEntity(entity.startObject()
.array("scroll_id", scroll)
.endObject().string(), ContentType.APPLICATION_JSON);
} catch (IOException e) {
throw new ElasticsearchException("failed to build clear scroll entity", e);
}
}
示例5: testLookupRemoteVersion
import org.apache.http.entity.ContentType; //导入依赖的package包/类
public void testLookupRemoteVersion() throws Exception {
AtomicBoolean called = new AtomicBoolean();
sourceWithMockedRemoteCall(false, ContentType.APPLICATION_JSON, "main/0_20_5.json").lookupRemoteVersion(v -> {
assertEquals(Version.fromString("0.20.5"), v);
called.set(true);
});
assertTrue(called.get());
called.set(false);
sourceWithMockedRemoteCall(false, ContentType.APPLICATION_JSON, "main/0_90_13.json").lookupRemoteVersion(v -> {
assertEquals(Version.fromString("0.90.13"), v);
called.set(true);
});
assertTrue(called.get());
called.set(false);
sourceWithMockedRemoteCall(false, ContentType.APPLICATION_JSON, "main/1_7_5.json").lookupRemoteVersion(v -> {
assertEquals(Version.fromString("1.7.5"), v);
called.set(true);
});
assertTrue(called.get());
called.set(false);
sourceWithMockedRemoteCall(false, ContentType.APPLICATION_JSON, "main/2_3_3.json").lookupRemoteVersion(v -> {
assertEquals(Version.V_2_3_3, v);
called.set(true);
});
assertTrue(called.get());
called.set(false);
sourceWithMockedRemoteCall(false, ContentType.APPLICATION_JSON, "main/5_0_0_alpha_3.json").lookupRemoteVersion(v -> {
assertEquals(Version.V_5_0_0_alpha3, v);
called.set(true);
});
assertTrue(called.get());
called.set(false);
sourceWithMockedRemoteCall(false, ContentType.APPLICATION_JSON, "main/with_unknown_fields.json").lookupRemoteVersion(v -> {
assertEquals(Version.V_5_0_0_alpha3, v);
called.set(true);
});
assertTrue(called.get());
}
示例6: doPost
import org.apache.http.entity.ContentType; //导入依赖的package包/类
/**
* Makes an HTTP POST request using the given URI and optional body.
*
* @param uri the URI to use for the POST call
* @param json Optional, can be null. the JSON to POST
* @return the resulting HttpFuture instance
*/
public HttpFuture doPost( URI uri, JsonNode json ) {
HttpPost httpPost = new HttpPost( uri );
String body = null;
if( json != null ) {
body = jsonHelper.serialize( json );
httpPost.setEntity( new NStringEntity( body, ContentType.create( "application/json", "UTF-8" ) ) );
}
return new HttpFuture( this, httpPost, asyncClient.execute( httpPost, null ), body );
}
示例7: testPerformRequestOnResponseExceptionWithEntity
import org.apache.http.entity.ContentType; //导入依赖的package包/类
public void testPerformRequestOnResponseExceptionWithEntity() throws IOException {
MainRequest mainRequest = new MainRequest();
CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
new Request("GET", "/", Collections.emptyMap(), null);
RestStatus restStatus = randomFrom(RestStatus.values());
HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
httpResponse.setEntity(new StringEntity("{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}",
ContentType.APPLICATION_JSON));
Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
ResponseException responseException = new ResponseException(mockResponse);
when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
anyObject(), anyVararg())).thenThrow(responseException);
ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
() -> restHighLevelClient.performRequest(mainRequest, requestConverter,
response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
assertEquals("Elasticsearch exception [type=exception, reason=test error message]", elasticsearchException.getMessage());
assertEquals(restStatus, elasticsearchException.status());
assertSame(responseException, elasticsearchException.getSuppressed()[0]);
}
示例8: testPerformRequestOnResponseExceptionWithBrokenEntity
import org.apache.http.entity.ContentType; //导入依赖的package包/类
public void testPerformRequestOnResponseExceptionWithBrokenEntity() throws IOException {
MainRequest mainRequest = new MainRequest();
CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
new Request("GET", "/", Collections.emptyMap(), null);
RestStatus restStatus = randomFrom(RestStatus.values());
HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
httpResponse.setEntity(new StringEntity("{\"error\":", ContentType.APPLICATION_JSON));
Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
ResponseException responseException = new ResponseException(mockResponse);
when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
anyObject(), anyVararg())).thenThrow(responseException);
ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
() -> restHighLevelClient.performRequest(mainRequest, requestConverter,
response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
assertEquals("Unable to parse response body", elasticsearchException.getMessage());
assertEquals(restStatus, elasticsearchException.status());
assertSame(responseException, elasticsearchException.getCause());
assertThat(elasticsearchException.getSuppressed()[0], instanceOf(JsonParseException.class));
}
示例9: testUpdate
import org.apache.http.entity.ContentType; //导入依赖的package包/类
/**
* update a wine
*
* @param id
* wine id
*/
private void testUpdate(final int id) throws IOException {
final HttpPut httpput = new HttpPut(BASE_URI + RESOURCE);
httpput.setEntity(new StringEntity("{\"id\":" + id + ",\"name\":\"JU" + id + "\",\"grapes\":\"Grenache / Syrah\"," + "\"country\":\"France\","
+ "\"region\":\"Southern Rhone / Gigondas\"," + "\"year\":2009,\"picture\":\"saint_cosme.jpg\","
+ "\"description\":\"The aromas of fruit ...\"}", ContentType.APPLICATION_JSON));
final HttpResponse response = HTTP_CLIENT.execute(httpput);
Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getStatusLine().getStatusCode());
}
示例10: testResponseProcessing
import org.apache.http.entity.ContentType; //导入依赖的package包/类
public void testResponseProcessing() throws Exception {
ContentDecoder contentDecoder = mock(ContentDecoder.class);
IOControl ioControl = mock(IOControl.class);
HttpContext httpContext = mock(HttpContext.class);
HeapBufferedAsyncResponseConsumer consumer = spy(new HeapBufferedAsyncResponseConsumer(TEST_BUFFER_LIMIT));
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK");
HttpResponse httpResponse = new BasicHttpResponse(statusLine);
httpResponse.setEntity(new StringEntity("test", ContentType.TEXT_PLAIN));
//everything goes well
consumer.responseReceived(httpResponse);
consumer.consumeContent(contentDecoder, ioControl);
consumer.responseCompleted(httpContext);
verify(consumer).releaseResources();
verify(consumer).buildResult(httpContext);
assertTrue(consumer.isDone());
assertSame(httpResponse, consumer.getResult());
consumer.responseCompleted(httpContext);
verify(consumer, times(1)).releaseResources();
verify(consumer, times(1)).buildResult(httpContext);
}
示例11: toString
import org.apache.http.entity.ContentType; //导入依赖的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: proxyRequest
import org.apache.http.entity.ContentType; //导入依赖的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();
}
示例13: formData_contentType
import org.apache.http.entity.ContentType; //导入依赖的package包/类
@Test
public void formData_contentType() throws Exception {
HttpResponse<JsonNode> response = client.post(BASE_URL + "/echoMultipart")
.field("name", "Mark")
.asJson();
JSONArray contentTypeValues = response.getBody().getObject().getJSONObject("headers").getJSONArray(HttpHeaders.CONTENT_TYPE);
assertEquals(1, contentTypeValues.length());
assertEquals(ContentType.APPLICATION_FORM_URLENCODED.withCharset(Charsets.UTF_8).toString(), contentTypeValues.getString(0));
}
示例14: load
import org.apache.http.entity.ContentType; //导入依赖的package包/类
/**
* load the content of this page from a fetched HttpEntity.
* @param entity HttpEntity
* @param maxBytes The maximum number of bytes to read
* @throws Exception when load fails
*/
public void load(HttpEntity entity, int maxBytes) throws Exception {
contentType = null;
Header type = entity.getContentType();
if (type != null) {
contentType = type.getValue();
}
contentEncoding = null;
Header encoding = entity.getContentEncoding();
if (encoding != null) {
contentEncoding = encoding.getValue();
}
Charset charset = ContentType.getOrDefault(entity).getCharset();
if (charset != null) {
contentCharset = charset.displayName();
}else {
contentCharset = Charset.defaultCharset().displayName();
}
contentData = toByteArray(entity, maxBytes);
}
示例15: handleResponse
import org.apache.http.entity.ContentType; //导入依赖的package包/类
private R handleResponse(ResponseParser<R> parser, HttpResponse response) throws IOException
{
StatusLine statusLine= response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK)
{
HttpEntity entity = response.getEntity();
if (entity != null)
{
Charset charset = ContentType.getOrDefault(entity).getCharset();
Reader reader = new InputStreamReader(entity.getContent(), charset);
return parser.parseResponse(reader);
}
throw new NextcloudApiException("Empty response received");
}
throw new NextcloudApiException(String.format("Request failed with %d %s", statusLine.getStatusCode(), statusLine.getReasonPhrase()));
}