Search in sources :

Example 1 with StringRequestEntity

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();
        }
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpException(org.apache.commons.httpclient.HttpException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 2 with StringRequestEntity

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);
                }
            }
        }
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) SpanEventRecorder(com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) URIException(org.apache.commons.httpclient.URIException) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 3 with StringRequestEntity

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);
    }
}
Also used : ZimbraCookie(com.zimbra.common.util.ZimbraCookie) Cookie(org.apache.commons.httpclient.Cookie) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) InputStreamReader(java.io.InputStreamReader) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpState(org.apache.commons.httpclient.HttpState) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Header(org.apache.commons.httpclient.Header) AuthScope(org.apache.commons.httpclient.auth.AuthScope) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with StringRequestEntity

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;
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) JSONObject(org.json.simple.JSONObject) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) JSONParser(org.json.simple.parser.JSONParser) IOException(java.io.IOException)

Example 5 with StringRequestEntity

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();
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) Language(org.intellij.lang.annotations.Language) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) Gson(com.google.gson.Gson)

Aggregations

StringRequestEntity (org.apache.commons.httpclient.methods.StringRequestEntity)100 PostMethod (org.apache.commons.httpclient.methods.PostMethod)62 HttpClient (org.apache.commons.httpclient.HttpClient)32 Test (org.junit.Test)23 PutMethod (org.apache.commons.httpclient.methods.PutMethod)19 RequestEntity (org.apache.commons.httpclient.methods.RequestEntity)18 IOException (java.io.IOException)15 UnsupportedEncodingException (java.io.UnsupportedEncodingException)13 AuthRequestHandler (org.apache.commons.httpclient.server.AuthRequestHandler)12 HttpRequestHandlerChain (org.apache.commons.httpclient.server.HttpRequestHandlerChain)12 HttpServiceHandler (org.apache.commons.httpclient.server.HttpServiceHandler)12 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)9 GetMethod (org.apache.commons.httpclient.methods.GetMethod)9 InputStream (java.io.InputStream)7 Header (org.apache.commons.httpclient.Header)7 InputStreamRequestEntity (org.apache.commons.httpclient.methods.InputStreamRequestEntity)7 StringWriter (java.io.StringWriter)6 Map (java.util.Map)6 PutMethod (org.apache.jackrabbit.webdav.client.methods.PutMethod)6 HashMap (java.util.HashMap)5