Java 类org.apache.http.entity.ContentType 实例源码
项目:Thrush
文件:HttpRequest.java
public static String checkRandCodeAnsyn(String randCode) {
Objects.requireNonNull(randCode);
ResultManager.touch(randCode, "confirmRandCode");
CloseableHttpClient httpClient = buildHttpClient();
HttpPost httpPost = new HttpPost(UrlConfig.checkRandCodeAnsyn);
httpPost.addHeader(CookieManager.cookieHeader());
httpPost.setEntity(new StringEntity(checkRandCodeAnsynParam(), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));
String result = StringUtils.EMPTY;
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
CookieManager.touch(response);
result = EntityUtils.toString(response.getEntity());
logger.debug(result);
} catch (IOException e) {
logger.error("checkRandCodeAnsyn error", e);
}
return result;
}
项目:logviewer
文件:GistCreator.java
/**
* 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;
}
项目:bootstrap
文件:CrudRestIT.java
/**
* create a wine
*
* @param id
* wine id
*/
private int create() throws IOException {
final HttpPost httppost = new HttpPost(BASE_URI + RESOURCE);
httppost.setEntity(new StringEntity(
"{\"name\":\"JUNIT" + "\",\"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(httppost);
try {
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
final String content = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
Assert.assertTrue(NumberUtils.isDigits(content));
return Integer.valueOf(content);
} finally {
response.getEntity().getContent().close();
}
}
项目:smn-sdk-java
文件:IAMServiceImpl.java
private AuthenticationBean postForIamToken(String iamUrl, String bodyMessage, ClientConfiguration clientConfiguration) throws Exception {
LOGGER.debug("Start to get iam token. IamUrl is {}.", iamUrl);
CloseableHttpClient httpclient = HttpUtil.getHttpClient(clientConfiguration);
try {
HttpPost httpPost = new HttpPost(iamUrl);
httpPost.setConfig(HttpUtil.getRequestConfig(clientConfiguration));
httpPost.addHeader("Content-Type", "application/json");
httpPost.setEntity(new StringEntity(bodyMessage, ContentType.APPLICATION_JSON));
// execute HTTPS post
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
int status = response.getStatusLine().getStatusCode();
// The length of the response will not be too long
HttpEntity entity = response.getEntity();
String responseMessage = entity != null ? EntityUtils.toString(entity) : null;
if (status >= 200 && status < 300) {
AuthenticationBean authBean = new AuthenticationBean();
// get IAM token
authBean.setAuthToken(response.getFirstHeader(X_SUBJECT_TOKEN).getValue());
Map<String, Object> messageMap = JsonUtil.parseJsonMessage(responseMessage);
// set projectId
authBean.setProjectId(parseProjectId(messageMap));
// set expires at
authBean.setExpiresAt(((Map) messageMap.get(TOKEN)).get(EXPIRES_AT).toString());
LOGGER.debug("End to get iam token. Status is {}. AuthBean is {}.", status, authBean);
return authBean;
} else {
LOGGER.error("Unexpected response status: {}. ErrorMessage is {}.", status, responseMessage);
throw new RuntimeException(
"Unexpected response status: " + status + ", ErrorMessage is " + responseMessage);
}
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
项目:legendarybot
文件:WoWUtils.java
/**
* Retrieve the informatoin of a realm
* @param bot The bot instance.
* @param region The region the realm is in
* @param realm The realm name
* @return A Json string containing information about the realm. Returns null if no realm is found.
*/
public static String getRealmInformation(LegendaryBot bot, String region, String realm) {
HttpEntity entity = new NStringEntity("{ \"query\": { \"match\" : { \"name\" : \""+realm+"\" } } }", ContentType.APPLICATION_JSON);
try {
Response response = bot.getElasticSearch().performRequest("POST", "/wow/realm_"+region.toLowerCase()+"/_search", Collections.emptyMap(), entity);
String jsonResponse = EntityUtils.toString(response.getEntity());
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(jsonResponse);
JSONArray hit = (JSONArray) ((JSONObject)obj.get("hits")).get("hits");
if (hit.size() == 0) {
return null;
}
JSONObject firstItem = (JSONObject) hit.get(0);
JSONObject source = (JSONObject) firstItem.get("_source");
return source.toJSONString();
} catch (IOException | ParseException e) {
e.printStackTrace();
}
return null;
}
项目:tangyuan2
文件:HttpRpcClient.java
private String sendPostRequest(String url, byte[] buffer, String header) throws Throwable {
// TODO: 默认值设置
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
URI uri = new URI(url);
HttpPost httpost = new HttpPost(uri);
ByteArrayEntity byteArrayEntity = new ByteArrayEntity(buffer, ContentType.create(header, "UTF-8"));
httpost.setEntity(byteArrayEntity);
CloseableHttpResponse response = httpclient.execute(httpost);
try {
int status = response.getStatusLine().getStatusCode();
if (status != 200) {
throw new Exception("Unexpected response status: " + status);
}
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, "UTF-8");
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
项目:codescene-jenkins-plugin
文件:DeltaAnalysis.java
private HttpPost createRequestFor(final DeltaAnalysisRequest payload) throws URISyntaxException {
final CodeSceneUser user = config.user();
final Header authorization = new BasicHeader("Authorization", "Basic " + user.asBase64Encoded());
HttpPost codeSceneRequest = new HttpPost(config.codeSceneUrl().toURI());
codeSceneRequest.addHeader(authorization);
StringEntity requestEntity = new StringEntity(
payload.asJson().toString(),
ContentType.APPLICATION_JSON);
codeSceneRequest.setEntity(requestEntity);
return codeSceneRequest;
}
项目:Thrush
文件:HttpRequest.java
public static String uamtk() {
CloseableHttpClient httpClient = buildHttpClient();
HttpPost httpPost = new HttpPost(UrlConfig.uamtk);
httpPost.addHeader(CookieManager.cookieHeader());
httpPost.setEntity(new StringEntity("appid=otn", 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);
ResultManager.touch(result, new ResultKey("tk", "newapptk"));
} catch (IOException e) {
logger.error("uamtk error", e);
}
return result;
}
项目:Thrush
文件:HttpRequest.java
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;
}
项目:Thrush
文件:HttpRequest.java
public static String submitOrderRequest(Ticket ticket, TrainQuery query) {
CloseableHttpClient httpClient = buildHttpClient();
HttpPost httpPost = new HttpPost(UrlConfig.submitOrderRequest);
httpPost.addHeader(CookieManager.cookieHeader());
String param = genSubmitOrderRequestParam(ticket, query);
httpPost.setEntity(new StringEntity(param, ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));
String result = StringUtils.EMPTY;
try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
CookieManager.touch(response);
result = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
logger.error("checkUser error", e);
}
return result;
}
项目:Thrush
文件:HttpRequest.java
public static String getQueueCount(Ticket ticket, TrainQuery query) {
CloseableHttpClient httpClient = buildHttpClient();
HttpPost httpPost = new HttpPost(UrlConfig.getQueueCount);
httpPost.addHeader(CookieManager.cookieHeader());
httpPost.setEntity(new StringEntity(getQueueCountParam(ticket, query), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));
String result = StringUtils.EMPTY;
try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
CookieManager.touch(response);
result = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
logger.error("getQueueCount error", e);
}
return result;
}
项目:Cognizant-Intelligent-Test-Scripter
文件:WebDriverFactory.java
private static Boolean addGeckoDriverAddon(File addonLoc, String url) {
try {
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
Map<String, Object> addonInfo = new HashMap<>();
addonInfo.put("temporary", true);
addonInfo.put("path", addonLoc.getAbsolutePath());
String json = new Gson().toJson(addonInfo);
StringEntity requestEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
post.setEntity(requestEntity);
return client.execute(post).getStatusLine().getStatusCode() == 200;
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
return false;
}
项目:DraytonWiser
文件:DraytonWiserConnection.java
public void setRoomTemperature(String WEBSERVICE_URL, String AUTHTOKEN, String roomName, int newTemp) {
try {
// Find room ID based on name
String roomId = getRoomID(WEBSERVICE_URL, AUTHTOKEN, roomName);
CloseableHttpClient http = HttpClientBuilder.create().build();
String payload = "{\"RequestOverride\":{\"Type\":\"Manual\",\"SetPoint\":" + Integer.toString(newTemp)
+ " }}";
HttpPatch updateRequest = new HttpPatch("http://192.168.3.6/data/domain/Room/" + roomId);
updateRequest.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
updateRequest.setHeader("SECRET", AUTHTOKEN);
HttpResponse response = http.execute(updateRequest);
String out = response.getEntity().toString();
logger.debug(out);
} catch (IOException e) {
logger.warn("Communication error occurred while getting your Drayton Wiser information: {}",
e.getMessage());
}
}
项目:rubenlagus-TelegramBots
文件:DefaultAbsSender.java
@Override
protected final <T extends Serializable, Method extends BotApiMethod<T>> T sendApiMethod(Method method) throws TelegramApiException {
method.validate();
String responseContent;
try {
String url = getBaseUrl() + method.getMethod();
HttpPost httppost = new HttpPost(url);
httppost.setConfig(requestConfig);
httppost.addHeader("charset", StandardCharsets.UTF_8.name());
httppost.setEntity(new StringEntity(objectMapper.writeValueAsString(method), ContentType.APPLICATION_JSON));
try (CloseableHttpResponse response = httpclient.execute(httppost)) {
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8);
}
} catch (IOException e) {
throw new TelegramApiException("Unable to execute " + method.getMethod() + " method", e);
}
return method.deserializeResponse(responseContent);
}
项目:elasticsearch_my
文件:Netty4HeadBodyIsEmptyIT.java
public void testTemplateExists() throws IOException {
try (XContentBuilder builder = jsonBuilder()) {
builder.startObject();
{
builder.array("index_patterns", "*");
builder.startObject("settings");
{
builder.field("number_of_replicas", 0);
}
builder.endObject();
}
builder.endObject();
client().performRequest("PUT", "/_template/template", emptyMap(),
new StringEntity(builder.string(), ContentType.APPLICATION_JSON));
headTestCase("/_template/template", emptyMap(), greaterThan(0));
}
}
项目:flow-platform
文件:CmdServiceImpl.java
/**
* Send cmd to control center cmd queue
*
* @throws HttpException
* @throws IllegalStatusException
*/
private Cmd sendToQueue(CmdInfo cmdInfo, int priority, int retry) {
final String url = HttpURL.build(platformURL.getQueueUrl())
.withParam("priority", Integer.toString(priority))
.withParam("retry", Integer.toString(retry))
.toString();
try {
HttpResponse<String> response = HttpClient.build(url)
.post(cmdInfo.toJson())
.withContentType(ContentType.APPLICATION_JSON)
.retry(httpRetryTimes)
.bodyAsString();
if (!response.hasSuccess()) {
final String message = "Create session cmd to queue failure for url: " + url;
throw new HttpException(message);
}
return Jsonable.parse(response.getBody(), Cmd.class);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Unable to send cmd since: ", e);
}
}
项目:elasticsearch_my
文件:Request.java
static Request index(IndexRequest indexRequest) {
String method = Strings.hasLength(indexRequest.id()) ? HttpPut.METHOD_NAME : HttpPost.METHOD_NAME;
boolean isCreate = (indexRequest.opType() == DocWriteRequest.OpType.CREATE);
String endpoint = endpoint(indexRequest.index(), indexRequest.type(), indexRequest.id(), isCreate ? "_create" : null);
Params parameters = Params.builder();
parameters.withRouting(indexRequest.routing());
parameters.withParent(indexRequest.parent());
parameters.withTimeout(indexRequest.timeout());
parameters.withVersion(indexRequest.version());
parameters.withVersionType(indexRequest.versionType());
parameters.withPipeline(indexRequest.getPipeline());
parameters.withRefreshPolicy(indexRequest.getRefreshPolicy());
parameters.withWaitForActiveShards(indexRequest.waitForActiveShards());
BytesRef source = indexRequest.source().toBytesRef();
ContentType contentType = ContentType.create(indexRequest.getContentType().mediaType());
HttpEntity entity = new ByteArrayEntity(source.bytes, source.offset, source.length, contentType);
return new Request(method, endpoint, parameters.getParams(), entity);
}
项目:elasticsearch_my
文件:RestHighLevelClientTests.java
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]);
}
项目:elasticsearch_my
文件:RestHighLevelClientTests.java
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));
}
项目:elasticsearch_my
文件:HeapBufferedAsyncResponseConsumerTests.java
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);
}
项目:fastcrawler
文件:Page.java
/**
* 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);
}
项目:nextcloud-java-api
文件:ConnectorCommon.java
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()));
}
项目:slacklet
文件:SlackWebSocketSessionImpl.java
private void postSlackCommandWithFile(Map<String, String> params, byte [] fileContent, String fileName, String command, SlackMessageHandleImpl handle) {
URIBuilder uriBuilder = new URIBuilder();
uriBuilder.setScheme(SLACK_API_SCHEME).setHost(SLACK_API_HOST).setPath(SLACK_API_PATH+"/"+command);
for (Map.Entry<String, String> arg : params.entrySet())
{
uriBuilder.setParameter(arg.getKey(),arg.getValue());
}
HttpPost request = new HttpPost(uriBuilder.toString());
HttpClient client = getHttpClient();
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
try
{
builder.addBinaryBody("file",fileContent, ContentType.DEFAULT_BINARY,fileName);
request.setEntity(builder.build());
HttpResponse response = client.execute(request);
String jsonResponse = ReaderUtils.readAll(new InputStreamReader(response.getEntity().getContent()));
LOGGER.debug("PostMessage return: " + jsonResponse);
ParsedSlackReply reply = SlackJSONReplyParser.decode(parseObject(jsonResponse),this);
handle.setReply(reply);
}
catch (Exception e)
{
// TODO : improve exception handling
e.printStackTrace();
}
}
项目:hustic
文件:IndexRequest.java
public IndexResponse execute() {
final HttpClient client = wrapper.getHttpClient();
IndexResponse indexResponse = null;
try {
final HttpPut httpPut = new HttpPut(this.path);
httpPut.setEntity(new StringEntity(this.data.toString(),
ContentType.APPLICATION_JSON));
System.out.println(this.data.toString());
indexResponse = client.execute(httpPut, new IndexResponseHandler());
} catch (IOException ioe) {
//TODO: Tham
}
return indexResponse;
}
项目:smarti
文件:RocketChatEndpoint.java
private void notifyRocketChat(String callbackUrl, Conversation conversation, String token) {
if (StringUtils.isBlank(callbackUrl)) return;
try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
final HttpPost post = new HttpPost(callbackUrl);
final MultiValueMap<String, String> props = CollectionUtils.toMultiValueMap(conversation.getMeta().getProperties());
post.setEntity(new StringEntity(
toJsonString(new SmartiUpdatePing(conversation.getId(), props.getFirst(ConversationMeta.PROP_CHANNEL_ID), token)),
ContentType.APPLICATION_JSON
));
httpClient.execute(post, response -> null);
} catch (IOException e) {
if (log.isDebugEnabled()) {
log.error("Callback to Rocket.Chat <{}> failed: {}", callbackUrl, e.getMessage(), e);
} else {
log.error("Callback to Rocket.Chat <{}> failed: {}", callbackUrl, e.getMessage());
}
}
}
项目:cloud-ariba-partner-flow-extension-ext
文件:OpenApisEndpoint.java
/**
* Performs HTTP Post request with OAuth authentication for the endpoint
* with the given path, with the given binary bodies as payload. Uses
* multipart/mixed content type.
*
* @param path
* the path to be called.
* @param binaryBodies
* the payload.
* @return the CloseableHttpResponse object.
* @throws ClientProtocolException
* @throws IOException
*/
CloseableHttpResponse executeHttpPost(String path, List<BinaryBody> binaryBodies)
throws ClientProtocolException, IOException {
logger.debug(DEBUG_EXECUTING_HTTP_POST_FOR_WITH_BINARY_BODIES, baseUri, path);
HttpPost httpPost = createHttpPost(baseUri + path);
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MULTIPART_MIXED_BOUNDARY);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
for (BinaryBody binaryBody : binaryBodies) {
multipartEntityBuilder.addBinaryBody(binaryBody.getBinaryBodyName(), binaryBody.getFileStream(),
ContentType.create(binaryBody.getMediaType()), binaryBody.getFileName());
}
HttpEntity httpEntity = multipartEntityBuilder.setBoundary(OpenApisEndpoint.BOUNDARY).build();
httpPost.setEntity(httpEntity);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpPost);
logger.debug(DEBUG_EXECUTED_HTTP_POST_FOR_WITH_BINARY_BODIES, baseUri, path);
return response;
}
项目:dotwebstack-framework
文件:ApiRequestValidatorTest.java
private ContainerRequestContext mockCtx() throws URISyntaxException {
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getPath()).thenReturn("/endpoint");
URI requestUri = new URI("/endpoint");
when(uriInfo.getRequestUri()).thenReturn(requestUri);
when(ctx.getUriInfo()).thenReturn(uriInfo);
when(ctx.getEntityStream()).thenReturn(mock(InputStream.class));
MultivaluedMap<String, String> pathParameters = new MultivaluedHashMap<>();
pathParameters.put(ID, ImmutableList.of(BPG));
pathParameters.put("random-header-parameter", ImmutableList.of(EPSG));
when(uriInfo.getPathParameters()).thenReturn(pathParameters);
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
headers.put("random-header-parameter", ImmutableList.of(EPSG));
headers.put(HttpHeaders.CONTENT_TYPE,
ImmutableList.of(ContentType.APPLICATION_JSON.toString()));
when(ctx.getHeaders()).thenReturn(headers);
return ctx;
}
项目:message-broker
文件:QueuesRestApiTest.java
@Test
public void testDuplicateQueueCreation() throws IOException {
QueueCreateRequest request = new QueueCreateRequest()
.name("testDuplicateQueueCreation").durable(false).autoDelete(false);
HttpPost httpPost = new HttpPost(apiBasePath + "/queues");
String value = objectMapper.writeValueAsString(request);
StringEntity stringEntity = new StringEntity(value, ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = client.execute(httpPost);
Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED, "Incorrect status code");
response = client.execute(httpPost);
Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_BAD_REQUEST, "Incorrect status "
+ "code");
String body = EntityUtils.toString(response.getEntity());
Error error = objectMapper.readValue(body, Error.class);
Assert.assertFalse(error.getMessage().isEmpty(), "Response body shouldn't be empty");
}
项目:integration-test-helper
文件:AomHttpClient.java
/**
* Adds an auth class in a module to the app
*
* @param customerName the name of the customer which owns the app
* @param appName the name of the app
* @param moduleName the name of the module containing the auth class
* @param className the name of the auth class
* @return request object to check status codes and return values
* @throws UnsupportedEncodingException exc
*/
public Response addAuthModuleToApp( String customerName, String appName, String moduleName,
String className )
throws UnsupportedEncodingException
{
final HttpPut request =
new HttpPut( this.yambasBase + "customers/" + customerName + "/apps/" + appName );
setAuthorizationHeader( request );
request.addHeader( "x-apiomat-system", this.system.toString( ) );
final String data =
"{ \"authClassesMap\" : { \"" + this.system.toString( ) + "\": { \"1\":\"Basics$User\", \"2\": \"" +
moduleName + "$" + className +
"\"}}}";
request.setEntity( new StringEntity( data, ContentType.APPLICATION_JSON ) );
try
{
final HttpResponse response = this.client.execute( request );
return new Response( response );
}
catch ( final IOException e )
{
e.printStackTrace( );
}
return null;
}
项目:stock-api-sdk
文件:HttpUtilsTest.java
@Test(groups = "HttpUtils.doPost")
public void doPost_should_throw_stockexception_since_httpClient_execute_returned_with_bad_request()
throws ClientProtocolException, IOException {
String errorResponse = "{ \"error\": { \"message\": \"Test Response\" } }";
CloseableHttpResponse httpResponse = PowerMockito
.mock(CloseableHttpResponse.class);
StatusLine statusLine = PowerMockito.mock(StatusLine.class);
StringEntity entity = new StringEntity(errorResponse);
PowerMockito.spy(HttpUtils.class);
try {
PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
"initialize");
} catch (Exception e1) {
Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
}
// and:
PowerMockito.when(statusLine.getStatusCode()).thenReturn(400);
PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);
PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
.thenReturn(httpResponse);
try {
HttpUtils.doPost("http://example.com", null,
errorResponse.getBytes(), ContentType.TEXT_PLAIN);
Assert.fail("Expected the StockException since the httpclient.execute returned with bad request!");
} catch (StockException e) {
Assert.assertEquals(e.getMessage(), errorResponse);
Assert.assertEquals(e.getCode(), 400);
}
}
项目:Tenable.io-SDK-for-Java
文件:AsyncHttpService.java
/**
* Makes an HTTP PUT request using the given URI and optional byte array body and headers.
*
* @param uri the URI to use for the PUT call
* @param contentType The content-type. Use helper function org.apache.http.entity.ContentType.create() to generate
* @param body Optional, can be null. An byte array that will be PUTed as is
* @param headers Optional, can be null. One or more HTTP headers, typically created by instancing org.apache.http.message.BasicHeader
* @return the resulting HttpFuture instance
*/
public HttpFuture doPut( URI uri, ContentType contentType, byte[] body, Header[] headers ) {
HttpPut httpPut = new HttpPut( uri );
if( body != null ) {
httpPut.setEntity( new NByteArrayEntity( body, contentType ) );
}
if( headers != null && headers.length > 0 )
httpPut.setHeaders( headers );
return new HttpFuture( this, httpPut, asyncClient.execute( httpPut, null ), null );
}
项目:flow-platform
文件:CmdServiceImpl.java
/**
* Send cmd to control center directly
*/
private Cmd sendDirectly(CmdInfo cmdInfo) throws UnsupportedEncodingException {
HttpResponse<String> response = HttpClient.build(platformURL.getCmdUrl())
.post(cmdInfo.toJson())
.withContentType(ContentType.APPLICATION_JSON)
.retry(httpRetryTimes)
.bodyAsString();
if (!response.hasSuccess()) {
throw new HttpException(String.format("Send cmd failure: %s", cmdInfo.getExtra()));
}
return Jsonable.parse(response.getBody(), Cmd.class);
}
项目:Reer
文件:HttpResourceUploader.java
public void upload(LocalResource resource, URI destination) throws IOException {
HttpPut method = new HttpPut(destination);
final RepeatableInputStreamEntity entity = new RepeatableInputStreamEntity(resource, ContentType.APPLICATION_OCTET_STREAM);
method.setEntity(entity);
CloseableHttpResponse response = null;
try {
response = http.performHttpRequest(method);
if (!http.wasSuccessful(response)) {
throw new IOException(String.format("Could not PUT '%s'. Received status code %s from server: %s",
destination, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
}
} finally {
HttpClientUtils.closeQuietly(response);
}
}
项目:QMark
文件:ClientMultipartFormPost.java
public static HttpEntity makeMultipartEntity(List<NameValuePair> params, final Map<String, File> files) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //如果有SocketTimeoutException等情况,可修改这个枚举
//builder.setCharset(Charset.forName("UTF-8")); //不要用这个,会导致服务端接收不到参数
if (params != null && params.size() > 0) {
for (NameValuePair p : params) {
builder.addTextBody(p.getName(), p.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8"));
}
}
if (files != null && files.size() > 0) {
Set<Entry<String, File>> entries = files.entrySet();
for (Entry<String, File> entry : entries) {
builder.addPart(entry.getKey(), new FileBody(entry.getValue()));
}
}
return builder.build();
}
项目:Photato
文件:ImageHandler.java
@Override
protected HttpEntity getEntity(String path, Map<String, String> query, File localFile) throws IOException {
String extension = FileHelper.getExtension(path);
ContentType contentType = ContentType.create(getContentType(extension.toLowerCase()));
return new FileEntity(localFile, contentType);
}
项目:integration-test-helper
文件:AomHttpClient.java
/**
* Adds a reference to an object
*
* @param moduleName
* the name of the module
* @param dataModelName
* the name of the datamodel
* @param dataModelId
* the id of the datamodel
* @param attributeName
* the name of the (reference) attribute
* @param refId
* the reference id
* @param isTransientRef
* indicates whether the referenced class is transient or not (needed to specify whether to set foreignId
* or id
* @param refClassModule
* the module name of the referenced class
* @param refClassName
* the name of the referenced class
* @return request object to check status codes and return values
*/
public Response addReference( String moduleName, String dataModelName, String dataModelId,
String attributeName,
String refId, boolean isTransientRef, String refClassModule, String refClassName )
{
final HttpPost request =
new HttpPost( this.yambasBase + "apps/" + this.appName + "/models/" + moduleName + "/" +
dataModelName + "/" + dataModelId + "/" + attributeName );
setAuthorizationHeader( request );
request.addHeader( "ContentType", "application/json" );
request.addHeader( "x-apiomat-apikey", this.apiKey );
request.addHeader( "x-apiomat-system", this.system.toString( ) );
try
{
final String data = "{ \"@type\":\"" + refClassModule + "$" + refClassName + "\",\"" +
( isTransientRef ? "foreignId" : "id" ) + "\":\"" + refId + "\"}";
final HttpEntity requestEntity = new StringEntity( data, 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;
}
项目:LDN4IIIF
文件:FetchRequest.java
public void setResponse(CloseableHttpResponse response) throws UnsupportedOperationException, IOException {
this.response = response;
if(response.getEntity()!=null) {
byte[] byteArray = IOUtils.toByteArray(response.getEntity().getContent());
ContentType contentType = ContentType.get(response.getEntity());
response.close();
this.content=new Content(byteArray, contentType);
}
}
项目:logregator
文件:HttpTransporter.java
public HttpTransporter(HttpTransporterConfig configuration) {
config = configuration;
subject = PublishSubject.create();
subject.subscribe(message -> {
try {
HttpPost request = new HttpPost(config.getUrl());
request.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));
config.getHttpClient().execute(request);
} catch (Exception e) {
log.error("Http transport fail", e);
}
});
}
项目:framework
文件:HttpUtils.java
/**
* post 请求
*
* @param url
* @param data
* @return
*/
private static String httpPost(String url, String data) {
try {
HttpEntity entity = Request.Post(url).bodyString(data, ContentType.create("text/html", Consts.UTF_8)).execute().returnResponse().getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} catch (Exception e) {
logger.error("post请求异常," + e.getMessage() + "\n post url:" + url);
e.printStackTrace();
}
return null;
}
项目:pay4j
文件:DefaultRequestExecutor.java
@Override
public FanmeiResponse post(String url, String body, Charset charset) throws RequestException {
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new StringEntity(body, ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset)));
CloseableHttpResponse response = httpClient.execute(httpPost);
return genFanmeiResponse(charset, response);
} catch (Exception e) {
throw RequestException.of(e);
}
}