List of usage examples for org.apache.http.entity ContentType create
public static ContentType create(String str, String str2) throws UnsupportedCharsetException
From source file:com.swisscom.refimpl.boundary.MIB2Client.java
public HttpResponse modifySubscription(String merchantId, String subscriptionId, List<HttpPut> out, String status) throws IOException, HttpException { HttpPut request = new HttpPut(MIB2Client.SUBSCRIPTIONS_URL + "/" + subscriptionId); String entity = "{\"operation\": \"" + status + "\"}"; request.setEntity(new StringEntity(entity, ContentType.create("application/vnd.ch.swisscom.easypay.subscription+json", "utf-8"))); if (out != null) { out.add(request);/* ww w. j a va 2s. co m*/ } addSignature(request, "PUT", "/subscriptions/" + subscriptionId, merchantId, "application/vnd.ch.swisscom.easypay.subscription+json", entity.getBytes("UTF-8")); return httpClient.execute(request); }
From source file:org.pepstock.jem.commands.util.HttpUtil.java
/** * Calls a http node of JEM to submit a job. * /*w ww . j av a2 s . c o m*/ * @param user user to authenticate * @param password password to authenticate * @param url http URL to call * @param prejob job instance to submit * @return job id * @throws SubmitException if errors occur */ public static String submit(String user, String password, String url, PreJob prejob) throws SubmitException { // creates a HTTP client CloseableHttpClient httpclient = null; boolean loggedIn = false; try { httpclient = createHttpClient(url); // prepares the entity to send via HTTP XStream streamer = new XStream(); String content = streamer.toXML(prejob); login(user, password, url, httpclient); loggedIn = true; // concats URL with query string String completeUrl = url + HttpUtil.SUBMIT_QUERY_STRING; StringEntity entity = new StringEntity(content, ContentType.create("text/xml", CharSet.DEFAULT_CHARSET_NAME)); // prepares POST request and basic response handler HttpPost httppost = new HttpPost(completeUrl); httppost.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); // executes and no parsing // result must be only a string String responseBody = httpclient.execute(httppost, responseHandler); return responseBody.trim(); } catch (KeyManagementException e) { throw new SubmitException(SubmitMessage.JEMW003E, e); } catch (UnrecoverableKeyException e) { throw new SubmitException(SubmitMessage.JEMW003E, e); } catch (NoSuchAlgorithmException e) { throw new SubmitException(SubmitMessage.JEMW003E, e); } catch (KeyStoreException e) { throw new SubmitException(SubmitMessage.JEMW003E, e); } catch (URISyntaxException e) { throw new SubmitException(SubmitMessage.JEMW003E, e); } catch (ClientProtocolException e) { throw new SubmitException(SubmitMessage.JEMW003E, e); } catch (IOException e) { throw new SubmitException(SubmitMessage.JEMW003E, e); } finally { if (loggedIn) { try { logout(url, httpclient); } catch (Exception e) { // debug LogAppl.getInstance().debug(e.getMessage(), e); } } // close http client if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { LogAppl.getInstance().ignore(e.getMessage(), e); } } } }
From source file:org.perfcake.message.sender.HttpClientSender.java
@Override public void preSend(final Message message, final Properties messageAttributes) throws Exception { super.preSend(message, messageAttributes); if (storeCookies && localCookieManager.get() == null) { localCookieManager.set(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); }//from w ww . ja v a2 s. c o m currentMethod = getDynamicMethod(messageAttributes); payloadLength = 0; if (message == null) { payload = null; } else if (message.getPayload() != null) { payload = message.getPayload().toString(); payloadLength = payload.length(); } final URI uri = url.toURI(); switch (currentMethod) { case GET: currentRequest = new HttpGet(uri); break; case POST: currentRequest = new HttpPost(uri); break; case PUT: currentRequest = new HttpPut(uri); break; case PATCH: currentRequest = new HttpPatch(uri); break; case DELETE: currentRequest = new HttpDelete(uri); break; case HEAD: currentRequest = new HttpHead(uri); break; case TRACE: currentRequest = new HttpTrace(uri); break; case OPTIONS: currentRequest = new HttpOptions(uri); } StringEntity msg = null; if (payload != null && (currentRequest instanceof HttpEntityEnclosingRequestBase)) { ((HttpEntityEnclosingRequestBase) currentRequest).setEntity( new StringEntity(payload, ContentType.create("text/plain", Utils.getDefaultEncoding()))); } if (storeCookies) { popCookies(); } if (log.isDebugEnabled()) { log.debug("Setting HTTP headers: "); } // set message properties as HTTP headers if (message != null) { for (final Entry<Object, Object> property : message.getProperties().entrySet()) { final String pKey = property.getKey().toString(); final String pValue = property.getValue().toString(); currentRequest.setHeader(pKey, pValue); if (log.isDebugEnabled()) { log.debug(pKey + ": " + pValue); } } } // set message headers as HTTP headers if (message != null) { if (message.getHeaders().size() > 0) { for (final Entry<Object, Object> property : message.getHeaders().entrySet()) { final String pKey = property.getKey().toString(); final String pValue = property.getValue().toString(); currentRequest.setHeader(pKey, pValue); if (log.isDebugEnabled()) { log.debug(pKey + ": " + pValue); } } } } if (log.isDebugEnabled()) { log.debug("End of HTTP headers."); } }
From source file:com.github.tomakehurst.wiremock.testsupport.WireMockTestClient.java
private int postJsonAndReturnStatus(String url, String json) { HttpPost post = new HttpPost(url); try {// w w w . j ava2 s .co m if (json != null) { post.setEntity(new StringEntity(json, ContentType.create(JSON.toString(), "utf-8"))); } HttpResponse httpResponse = httpClient().execute(post); return httpResponse.getStatusLine().getStatusCode(); } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.kaaproject.kaa.server.appenders.rest.appender.RestLogAppender.java
private ContentType buildContentType(RestConfig configuration) { ContentType contentType;/*ww w .j a v a 2s. c om*/ if (configuration.getMimeType() == RequestType.TEXT) { contentType = ContentType.create("text/plain", "UTF-8"); } else { contentType = ContentType.create("application/json", "UTF-8"); } return contentType; }
From source file:org.apache.marmotta.platform.core.services.http.HttpClientServiceImpl.java
@Override public String doPost(String url, String body) throws IOException { return doPost(url, new StringEntity(body, ContentType.create("text/plain", DEFAULT_CHARSET)), new StringBodyResponseHandler()); }
From source file:com.ngdata.hbaseindexer.indexer.FusionPipelineClient.java
protected FusionSession establishSession(String url, String user, String password, String realm) throws Exception { FusionSession fusionSession = new FusionSession(); if (!isKerberos && realm != null) { int at = url.indexOf("/api"); String proxyUrl = url.substring(0, at); String sessionApi = proxyUrl + "/api/session?realmName=" + realm; String jsonString = "{\"username\":\"" + user + "\", \"password\":\"" + password + "\"}"; // TODO: ugly! URL sessionApiUrl = new URL(sessionApi); String sessionHost = sessionApiUrl.getHost(); try {// w w w .j a va 2 s . c o m clearCookieForHost(sessionHost); } catch (Exception exc) { log.warn("Failed to clear session cookie for " + sessionHost + " due to: " + exc); } HttpPost postRequest = new HttpPost(sessionApiUrl.toURI()); postRequest.setEntity( new StringEntity(jsonString, ContentType.create("application/json", StandardCharsets.UTF_8))); HttpClientContext context = HttpClientContext.create(); context.setCookieStore(cookieStore); HttpResponse response = httpClient.execute(postRequest, context); HttpEntity entity = response.getEntity(); try { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200 && statusCode != 201 && statusCode != 204) { String body = extractResponseBodyText(entity); throw new SolrException(SolrException.ErrorCode.getErrorCode(statusCode), "POST credentials to Fusion Session API [" + sessionApi + "] failed due to: " + response.getStatusLine() + ": " + body); } else if (statusCode == 401) { // retry in case this is an expired error String body = extractResponseBodyText(entity); if (body != null && body.indexOf("session-idle-timeout") != -1) { EntityUtils.consume(entity); // have to consume the previous entity before re-trying the request log.warn( "Received session-idle-timeout error from Fusion Session API, re-trying to establish a new session to " + url); try { clearCookieForHost(sessionHost); } catch (Exception exc) { log.warn("Failed to clear session cookie for " + sessionHost + " due to: " + exc); } response = httpClient.execute(postRequest, context); entity = response.getEntity(); statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200 && statusCode != 201 && statusCode != 204) { body = extractResponseBodyText(entity); throw new SolrException(SolrException.ErrorCode.getErrorCode(statusCode), "POST credentials to Fusion Session API [" + sessionApi + "] failed due to: " + response.getStatusLine() + ": " + body); } } } } finally { if (entity != null) EntityUtils.consume(entity); } log.info("Established secure session with Fusion Session API on " + url + " for user " + user + " in realm " + realm); } fusionSession.sessionEstablishedAt = System.nanoTime(); URL fusionUrl = new URL(url); String hostAndPort = fusionUrl.getHost() + ":" + fusionUrl.getPort(); fusionSession.docsSentMeter = getMeterByHost("Docs Sent to Fusion", hostAndPort); return fusionSession; }
From source file:org.wisdom.framework.filters.ProxyFilter.java
/** * The interception method. Re-emit the request to the target folder and forward the response. This method * returns an {@link org.wisdom.api.http.AsyncResult} as the proxy need to be run in another thread. It also * invokes a couple of callbacks letting developers to customize the request and result. * * @param route the route//from w ww . j a v a 2s. c o m * @param context the filter context * @return the result * @throws Exception if anything bad happen */ @Override public Result call(final Route route, final RequestContext context) throws Exception { return new AsyncResult(new Callable<Result>() { @Override public Result call() throws Exception { URI rewrittenURI = rewriteURI(context); logger.debug("Proxy request - rewriting {} to {}", context.request().uri(), rewrittenURI); if (rewrittenURI == null) { return onRewriteFailed(context); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest( context.request().method(), rewrittenURI.toString()); // Any header listed by the Connection header must be removed: // http://tools.ietf.org/html/rfc7230#section-6.1. Set<String> hopHeaders = new HashSet<>(); List<String> connectionHeaders = context.request().headers().get(HeaderNames.CONNECTION); for (String s : connectionHeaders) { for (String entry : Splitter.on(",").omitEmptyStrings().trimResults().splitToList(s)) { hopHeaders.add(entry.toLowerCase(Locale.ENGLISH)); } } boolean hasContent = context.request().contentType() != null; final String host = getHost(); Multimap<String, String> headers = ArrayListMultimap.create(); for (Map.Entry<String, List<String>> entry : context.request().headers().entrySet()) { String name = entry.getKey(); if (HeaderNames.TRANSFER_ENCODING.equalsIgnoreCase(name)) { hasContent = true; } if (host != null && HeaderNames.HOST.equalsIgnoreCase(name)) { continue; } // Remove hop-by-hop headers. String lower = name.toLowerCase(Locale.ENGLISH); if (HOP_HEADERS.contains(lower) || hopHeaders.contains(lower)) { continue; } for (String v : entry.getValue()) { headers.put(name, v); } } // Force the Host header if configured headers.removeAll(HeaderNames.HOST); if (host != null) { headers.put(HeaderNames.HOST, host); headers.put("X-Forwarded-Server", host); } else { // Set of the URI one headers.put("X-Forwarded-Server", rewrittenURI.getHost()); } // Add proxy headers if (getVia() != null) { headers.put(HeaderNames.VIA, "http/1.1 " + getVia()); } headers.put("X-Forwarded-For", context.request().remoteAddress()); if (host != null) { headers.put("X-Forwarded-Host", host); } updateHeaders(context, headers); for (Map.Entry<String, String> s : headers.entries()) { request.addHeader(s.getKey(), s.getValue()); } // Remove content-length as it is computed by the HTTP client. request.removeHeaders(HeaderNames.CONTENT_LENGTH); if (hasContent) { ByteArrayEntity entity = new ByteArrayEntity(context.context().raw(), ContentType .create(context.request().contentMimeType(), context.request().contentCharset())); request.setEntity(entity); } HttpResponse response = client.execute(new HttpHost(rewrittenURI.getHost(), rewrittenURI.getPort()), request); return onResult(toResult(response)); } }); }
From source file:org.duracloud.common.web.RestHttpHelper.java
private ContentType buildContentType(String mimeType) { ContentType contentType;/*from ww w . j a va 2 s .co m*/ if (null == mimeType) { contentType = ContentType.TEXT_XML; } else { contentType = ContentType.create(mimeType, StandardCharsets.UTF_8); } return contentType; }