Search in sources :

Example 26 with PostMethod

use of org.apache.commons.httpclient.methods.PostMethod in project tdi-studio-se by Talend.

the class ExchangeUtils method sendPostRequest.

public static String sendPostRequest(String urlAddress, Map<String, String> parameters) throws Exception {
    HttpClient httpclient = new HttpClient();
    PostMethod postMethod = new PostMethod(urlAddress);
    if (parameters != null) {
        NameValuePair[] postData = new NameValuePair[parameters.size()];
        int i = 0;
        for (String key : parameters.keySet()) {
            String value = parameters.get(key);
            postData[i++] = new NameValuePair(key, value);
        }
        postMethod.addParameters(postData);
    }
    httpclient.executeMethod(postMethod);
    String response = postMethod.getResponseBodyAsString();
    postMethod.releaseConnection();
    return response;
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient)

Example 27 with PostMethod

use of org.apache.commons.httpclient.methods.PostMethod in project tdi-studio-se by Talend.

the class MDMTransaction method commit.

public void commit() throws IOException {
    HttpClient client = new HttpClient();
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    HttpMethod method = new PostMethod(url + "/" + id);
    method.setDoAuthentication(true);
    try {
        //$NON-NLS-1$ //$NON-NLS-2$
        method.setRequestHeader("Cookie", getStickySession() + "=" + sessionId);
        client.executeMethod(method);
    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        method.releaseConnection();
    }
    int statuscode = method.getStatusCode();
    if (statuscode >= 400) {
        throw new MDMTransactionException("Commit failed. The commit operation has returned the code " + statuscode + ".");
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 28 with PostMethod

use of org.apache.commons.httpclient.methods.PostMethod in project tdi-studio-se by Talend.

the class SpagoBITalendEngineClient_0_5_0 method deployJob.

/*
     * (non-Javadoc)
     * 
     * @see
     * it.eng.spagobi.engines.talend.client.ISpagoBITalendEngineClient#deployJob(it.eng.spagobi.engines.talend.client
     * .JobDeploymentDescriptor, java.io.File)
     */
public boolean deployJob(JobDeploymentDescriptor jobDeploymentDescriptor, File executableJobFiles) throws EngineUnavailableException, AuthenticationFailedException, ServiceInvocationFailedException {
    HttpClient client;
    PostMethod method;
    File deploymentDescriptorFile;
    boolean result = false;
    client = new HttpClient();
    method = new PostMethod(getServiceUrl(JOB_UPLOAD_SERVICE));
    deploymentDescriptorFile = null;
    try {
        //$NON-NLS-1$ //$NON-NLS-2$
        deploymentDescriptorFile = File.createTempFile("deploymentDescriptor", ".xml");
        FileWriter writer = new FileWriter(deploymentDescriptorFile);
        writer.write(jobDeploymentDescriptor.toXml());
        writer.flush();
        writer.close();
        Part[] parts = { new FilePart(executableJobFiles.getName(), executableJobFiles), //$NON-NLS-1$
        new FilePart("deploymentDescriptor", deploymentDescriptorFile) };
        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(method);
        if (status == HttpStatus.SC_OK) {
            if (//$NON-NLS-1$
            method.getResponseBodyAsString().equalsIgnoreCase("OK"))
                result = true;
        } else {
            throw new ServiceInvocationFailedException(Messages.getString("SpagoBITalendEngineClient_0_5_0.serviceExcFailed") + JOB_UPLOAD_SERVICE, //$NON-NLS-1$
            method.getStatusLine().toString(), method.getResponseBodyAsString());
        }
    } catch (HttpException e) {
        //$NON-NLS-1$
        throw new EngineUnavailableException(Messages.getString("SpagoBITalendEngineClient_0_5_0.protocolViolation") + e.getMessage());
    } catch (IOException e) {
        //$NON-NLS-1$
        throw new EngineUnavailableException(Messages.getString("SpagoBITalendEngineClient_0_5_0.transportError") + e.getMessage());
    } finally {
        method.releaseConnection();
        if (deploymentDescriptorFile != null)
            deploymentDescriptorFile.delete();
    }
    return result;
}
Also used : ServiceInvocationFailedException(it.eng.spagobi.engines.talend.client.exception.ServiceInvocationFailedException) PostMethod(org.apache.commons.httpclient.methods.PostMethod) FileWriter(java.io.FileWriter) IOException(java.io.IOException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) EngineUnavailableException(it.eng.spagobi.engines.talend.client.exception.EngineUnavailableException) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) File(java.io.File)

Example 29 with PostMethod

use of org.apache.commons.httpclient.methods.PostMethod 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 30 with PostMethod

use of org.apache.commons.httpclient.methods.PostMethod in project zm-mailbox by Zimbra.

the class LmcSendMsgRequest method postAttachment.

/*
    * Post the attachment represented by File f and return the attachment ID
    */
public String postAttachment(String uploadURL, LmcSession session, File f, // cookie domain e.g. ".example.zimbra.com"
String domain, int msTimeout) throws LmcSoapClientException, IOException {
    String aid = null;
    // set the cookie.
    if (session == null)
        System.err.println(System.currentTimeMillis() + " " + Thread.currentThread() + " LmcSendMsgRequest.postAttachment session=null");
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    PostMethod post = new PostMethod(uploadURL);
    ZAuthToken zat = session.getAuthToken();
    Map<String, String> cookieMap = zat.cookieMap(false);
    if (cookieMap != null) {
        HttpState initialState = new HttpState();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            Cookie cookie = new Cookie(domain, ck.getKey(), ck.getValue(), "/", -1, false);
            initialState.addCookie(cookie);
        }
        client.setState(initialState);
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }
    post.getParams().setSoTimeout(msTimeout);
    int statusCode = -1;
    try {
        String contentType = URLConnection.getFileNameMap().getContentTypeFor(f.getName());
        Part[] parts = { new FilePart(f.getName(), f, contentType, "UTF-8") };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        statusCode = HttpClientUtil.executeMethod(client, post);
        // parse the response
        if (statusCode == 200) {
            // paw through the returned HTML and get the attachment id
            String response = post.getResponseBodyAsString();
            //System.out.println("response is\n" + response);
            int lastQuote = response.lastIndexOf("'");
            int firstQuote = response.indexOf("','") + 3;
            if (lastQuote == -1 || firstQuote == -1)
                throw new LmcSoapClientException("Attachment post failed, unexpected response: " + response);
            aid = response.substring(firstQuote, lastQuote);
        } else {
            throw new LmcSoapClientException("Attachment post failed, status=" + statusCode);
        }
    } catch (IOException e) {
        System.err.println("Attachment post failed");
        e.printStackTrace();
        throw e;
    } finally {
        post.releaseConnection();
    }
    return aid;
}
Also used : Cookie(org.apache.commons.httpclient.Cookie) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpState(org.apache.commons.httpclient.HttpState) IOException(java.io.IOException) ZAuthToken(com.zimbra.common.auth.ZAuthToken) HttpClient(org.apache.commons.httpclient.HttpClient) Map(java.util.Map)

Aggregations

PostMethod (org.apache.commons.httpclient.methods.PostMethod)203 HttpClient (org.apache.commons.httpclient.HttpClient)114 Test (org.junit.Test)55 IOException (java.io.IOException)32 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)28 Part (org.apache.commons.httpclient.methods.multipart.Part)25 NameValuePair (org.apache.commons.httpclient.NameValuePair)24 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)23 Map (java.util.Map)21 GetMethod (org.apache.commons.httpclient.methods.GetMethod)21 StringRequestEntity (org.apache.commons.httpclient.methods.StringRequestEntity)21 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)21 HttpMethod (org.apache.commons.httpclient.HttpMethod)17 Header (org.apache.commons.httpclient.Header)16 Note (org.apache.zeppelin.notebook.Note)13 HttpException (org.apache.commons.httpclient.HttpException)12 File (java.io.File)11 InputStream (java.io.InputStream)11 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)11 JSONParser (org.json.simple.parser.JSONParser)11