use of org.apache.commons.httpclient.methods.StringRequestEntity in project pinot by linkedin.
the class FileUploadUtils method sendSegmentJsonImpl.
public static int sendSegmentJsonImpl(final String host, final String port, final JSONObject segmentJson) {
PostMethod postMethod = null;
try {
RequestEntity requestEntity = new StringRequestEntity(segmentJson.toString(), ContentType.APPLICATION_JSON.getMimeType(), ContentType.APPLICATION_JSON.getCharset().name());
postMethod = new PostMethod("http://" + host + ":" + port + "/" + SEGMENTS_PATH);
postMethod.setRequestEntity(requestEntity);
postMethod.setRequestHeader(UPLOAD_TYPE, FileUploadType.JSON.toString());
int statusCode = FILE_UPLOAD_HTTP_CLIENT.executeMethod(postMethod);
if (statusCode >= 400) {
String errorString = "POST Status Code: " + statusCode + "\n";
if (postMethod.getResponseHeader("Error") != null) {
errorString += "ServletException: " + postMethod.getResponseHeader("Error").getValue();
}
throw new HttpException(errorString);
}
return statusCode;
} catch (Exception e) {
LOGGER.error("Caught exception while sending json: {}", segmentJson.toString(), e);
Utils.rethrowException(e);
throw new AssertionError("Should not reach this");
} finally {
if (postMethod != null) {
postMethod.releaseConnection();
}
}
}
use of org.apache.commons.httpclient.methods.StringRequestEntity in project pinpoint by naver.
the class HttpMethodBaseExecuteMethodInterceptor method recordEntity.
private void recordEntity(HttpMethod httpMethod, Trace trace) {
if (httpMethod instanceof EntityEnclosingMethod) {
final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;
final RequestEntity entity = entityEnclosingMethod.getRequestEntity();
if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
if (entitySampler.isSampling()) {
try {
String entityValue;
String charSet = entityEnclosingMethod.getRequestCharSet();
if (charSet == null || charSet.isEmpty()) {
charSet = HttpConstants.DEFAULT_CONTENT_CHARSET;
}
if (entity instanceof ByteArrayRequestEntity || entity instanceof StringRequestEntity) {
entityValue = entityUtilsToString(entity, charSet);
} else {
entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")";
}
final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
recorder.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, entityValue);
} catch (Exception e) {
logger.debug("HttpEntityEnclosingRequest entity record fail. Caused:{}", e.getMessage(), e);
}
}
}
}
}
use of org.apache.commons.httpclient.methods.StringRequestEntity in project zm-mailbox by Zimbra.
the class SoapHttpTransport method invoke.
public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId, String changeToken, String tokenType, ResponseHandler respHandler) throws IOException, HttpException, ServiceException {
PostMethod method = null;
try {
// Assemble post method. Append document name, so that the request
// type is written to the access log.
String uri, query;
int i = mUri.indexOf('?');
if (i >= 0) {
uri = mUri.substring(0, i);
query = mUri.substring(i);
} else {
uri = mUri;
query = "";
}
if (!uri.endsWith("/"))
uri += '/';
uri += getDocumentName(document);
method = new PostMethod(uri + query);
// Set user agent if it's specified.
String agentName = getUserAgentName();
if (agentName != null) {
String agentVersion = getUserAgentVersion();
if (agentVersion != null)
agentName += " " + agentVersion;
method.setRequestHeader(new Header("User-Agent", agentName));
}
// the content-type charset will determine encoding used
// when we set the request body
method.setRequestHeader("Content-Type", getRequestProtocol().getContentType());
if (getClientIp() != null) {
method.setRequestHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
if (ZimbraLog.misc.isDebugEnabled()) {
ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
}
}
Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken, tokenType);
String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
HttpMethodParams params = method.getParams();
method.setRequestEntity(new StringRequestEntity(soapMessage, null, "UTF-8"));
if (getRequestProtocol().hasSOAPActionHeader())
method.setRequestHeader("SOAPAction", mUri);
if (mCustomHeaders != null) {
for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) method.setRequestHeader(entry.getKey(), entry.getValue());
}
String host = method.getURI().getHost();
HttpState state = HttpClientUtil.newHttpState(getAuthToken(), host, this.isAdmin());
String trustedToken = getTrustedToken();
if (trustedToken != null) {
state.addCookie(new Cookie(host, ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken, "/", null, false));
}
params.setCookiePolicy(state.getCookies().length == 0 ? CookiePolicy.IGNORE_COOKIES : CookiePolicy.BROWSER_COMPATIBILITY);
params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(mRetryCount - 1, true));
params.setSoTimeout(mTimeout);
params.setVersion(HttpVersion.HTTP_1_1);
method.setRequestHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");
if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
state.setProxyCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword()));
}
if (mHttpDebugListener != null) {
mHttpDebugListener.sendSoapMessage(method, soapReq, state);
}
int responseCode = mClient.executeMethod(mHostConfig, method, state);
// real server issues will probably be "503" or "404"
if (responseCode != HttpServletResponse.SC_OK && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
throw ServiceException.PROXY_ERROR(method.getStatusLine().toString(), uri);
// Read the response body. Use the stream API instead of the byte[]
// version to avoid HTTPClient whining about a large response.
InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream(), SoapProtocol.getCharset());
String responseStr = "";
try {
if (respHandler != null) {
respHandler.process(reader);
return null;
} else {
responseStr = ByteUtil.getContent(reader, (int) method.getResponseContentLength(), false);
Element soapResp = parseSoapResponse(responseStr, raw);
if (mHttpDebugListener != null) {
mHttpDebugListener.receiveSoapMessage(method, soapResp);
}
return soapResp;
}
} catch (SoapFaultException x) {
// attach request/response to the exception and rethrow
x.setFaultRequest(soapMessage);
x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
throw x;
}
} finally {
// Release the connection to the connection manager
if (method != null)
method.releaseConnection();
// exits. Leave it here anyway.
if (!mKeepAlive)
mClient.getHttpConnectionManager().closeIdleConnections(0);
}
}
use of org.apache.commons.httpclient.methods.StringRequestEntity in project spatial-portal by AtlasOfLivingAustralia.
the class ToolComposer method processAdhoc.
JSONObject processAdhoc(String scientificName) {
String url = CommonData.getBiocacheServer() + "/process/adhoc";
try {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(url);
StringRequestEntity sre = new StringRequestEntity("{ \"scientificName\": \"" + scientificName.replace("\"", "'") + "\" } ", StringConstants.APPLICATION_JSON, StringConstants.UTF_8);
post.setRequestEntity(sre);
int result = client.executeMethod(post);
if (result == 200) {
JSONParser jp = new JSONParser();
return (JSONObject) jp.parse(post.getResponseBodyAsString());
}
} catch (Exception e) {
LOGGER.error("error processing species request: " + url + ", scientificName=" + scientificName, e);
}
return null;
}
use of org.apache.commons.httpclient.methods.StringRequestEntity in project intellij-community by JetBrains.
the class JiraIntegrationTest method createIssueViaRestApi.
// We can use XML-RPC in JIRA 5+ too, but nonetheless it's useful to have REST-based implementation as well
private String createIssueViaRestApi(@NotNull String project, @NotNull String summary) throws Exception {
final HttpClient client = myRepository.getHttpClient();
final PostMethod method = new PostMethod(myRepository.getUrl() + "/rest/api/latest/issue");
try {
// For simplicity assume that project, summary and username don't contain illegal characters
@Language("JSON") final String json = "{\"fields\": {\n" + " \"project\": {\n" + " \"key\": \"" + project + "\"\n" + " },\n" + " \"issuetype\": {\n" + " \"name\": \"Bug\"\n" + " },\n" + " \"assignee\": {\n" + " \"name\": \"" + myRepository.getUsername() + "\"\n" + " },\n" + " \"summary\": \"" + summary + "\"\n" + "}}";
method.setRequestEntity(new StringRequestEntity(json, "application/json", "utf-8"));
client.executeMethod(method);
return new Gson().fromJson(method.getResponseBodyAsString(), JsonObject.class).get("id").getAsString();
} finally {
method.releaseConnection();
}
}
Aggregations