Example usage for org.apache.commons.httpclient.methods PostMethod PostMethod

List of usage examples for org.apache.commons.httpclient.methods PostMethod PostMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod PostMethod.

Prototype

public PostMethod(String paramString) 

Source Link

Usage

From source file:be.fedict.trust.ocsp.OnlineOcspRepository.java

private OCSPResp getOcspResponse(URI ocspUri, X509Certificate certificate, X509Certificate issuerCertificate)
        throws OCSPException, IOException {
    LOG.debug("OCSP URI: " + ocspUri);
    OCSPReqGenerator ocspReqGenerator = new OCSPReqGenerator();
    CertificateID certId = new CertificateID(CertificateID.HASH_SHA1, issuerCertificate,
            certificate.getSerialNumber());
    ocspReqGenerator.addRequest(certId);
    OCSPReq ocspReq = ocspReqGenerator.generate();
    byte[] ocspReqData = ocspReq.getEncoded();

    PostMethod postMethod = new PostMethod(ocspUri.toString());
    RequestEntity requestEntity = new ByteArrayRequestEntity(ocspReqData, "application/ocsp-request");
    postMethod.addRequestHeader("User-Agent", "jTrust OCSP Client");
    postMethod.setRequestEntity(requestEntity);

    HttpClient httpClient = new HttpClient();
    if (null != this.networkConfig) {
        httpClient.getHostConfiguration().setProxy(this.networkConfig.getProxyHost(),
                this.networkConfig.getProxyPort());
    }/*from   ww w  .j a v  a2s.c  o m*/
    if (null != this.credentials) {
        HttpState httpState = httpClient.getState();
        this.credentials.init(httpState);
    }

    int responseCode;
    try {
        httpClient.executeMethod(postMethod);
        responseCode = postMethod.getStatusCode();
    } catch (ConnectException e) {
        LOG.debug("OCSP responder is down");
        return null;
    }

    if (HttpURLConnection.HTTP_OK != responseCode) {
        LOG.error("HTTP response code: " + responseCode);
        return null;
    }

    Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type");
    if (null == responseContentTypeHeader) {
        LOG.debug("no Content-Type response header");
        return null;
    }
    String resultContentType = responseContentTypeHeader.getValue();
    if (!"application/ocsp-response".equals(resultContentType)) {
        LOG.debug("result content type not application/ocsp-response");
        return null;
    }

    Header responseContentLengthHeader = postMethod.getResponseHeader("Content-Length");
    if (null != responseContentLengthHeader) {
        String resultContentLength = responseContentLengthHeader.getValue();
        if ("0".equals(resultContentLength)) {
            LOG.debug("no content returned");
            return null;
        }
    }

    OCSPResp ocspResp = new OCSPResp(postMethod.getResponseBodyAsStream());
    LOG.debug("OCSP response size: " + ocspResp.getEncoded().length + " bytes");
    return ocspResp;
}

From source file:com.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForNotificationsOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;
    PushResponse pushResponse;//w ww.  j a  v  a2  s  . c o  m
    PostMethod post = null;

    try {
        // Post Method
        String uri = Uri.parse(client.getBaseUri() + OCS_ROUTE).buildUpon()
                .appendQueryParameter(PUSH_TOKEN_HASH, pushTokenHash)
                .appendQueryParameter(DEVICE_PUBLIC_KEY, devicePublicKey)
                .appendQueryParameter(PROXY_SERVER, proxyServer).build().toString();

        post = new PostMethod(uri);
        post.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

        status = client.executeMethod(post);
        String response = post.getResponseBodyAsString();

        if (isSuccess(status)) {
            result = new RemoteOperationResult(true, status, post.getResponseHeaders());
            Log_OC.d(TAG, "Successful response: " + response);

            // Parse the response
            pushResponse = parseResult(response);
            result.setPushResponseData(pushResponse);
        } else {
            if (isInvalidSessionToken(response)) {
                result = new RemoteOperationResult(
                        RemoteOperationResult.ResultCode.ACCOUNT_USES_STANDARD_PASSWORD);
            } else {
                result = new RemoteOperationResult(false, status, post.getResponseHeaders());
            }
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception while registering device for notifications", e);

    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
    return result;
}

From source file:br.org.acessobrasil.silvinha.util.versoes.AtualizadorDeVersoes.java

public boolean baixarVersao() {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    NameValuePair param = new NameValuePair("param", "update");
    method.setRequestBody(new NameValuePair[] { param });
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    JFrame down = new JFrame("Download");
    File downFile = null;//from   w w  w.  ja  v  a 2  s. co  m
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + method.getStatusLine());
        }
        Header header = method.getResponseHeader("Content-Disposition");
        String fileName = "silvinha.exe";
        if (header != null) {
            fileName = header.getValue().split("=")[1];
        }
        // Read the response body.
        is = method.getResponseBodyAsStream();
        down.pack();
        ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(down,
                TradAtualizadorDeVersoes.FAZ_DOWNLOAD_FILE + fileName, is);
        pmis.getProgressMonitor().setMinimum(0);
        pmis.getProgressMonitor().setMaximum((int) method.getResponseContentLength());
        downFile = new File(fileName);
        fos = new FileOutputStream(downFile);
        int c;
        while (((c = pmis.read()) != -1) && (!pmis.getProgressMonitor().isCanceled())) {
            fos.write(c);
        }
        fos.flush();
        fos.close();
        String msgOK = TradAtualizadorDeVersoes.DOWNLOAD_EXITO
                + TradAtualizadorDeVersoes.DESEJA_ATUALIZAR_EXECUTAR + TradAtualizadorDeVersoes.ARQUIVO_DE_NOME
                + fileName + TradAtualizadorDeVersoes.LOCALIZADO_NA + TradAtualizadorDeVersoes.PASTA_INSTALACAO
                + TradAtualizadorDeVersoes.APLICACAO_DEVE_SER_ENCERRADA
                + TradAtualizadorDeVersoes.DESEJA_CONTINUAR_ATUALIZACAO;
        if (JOptionPane.showConfirmDialog(null, msgOK, TradAtualizadorDeVersoes.ATUALIZACAO_DO_PROGRAMA,
                JOptionPane.YES_NO_OPTION) == 0) {
            return true;
        } else {
            return false;
        }
    } catch (HttpException he) {
        log.error("Fatal protocol violation: " + he.getMessage(), he);
        return false;
    } catch (InterruptedIOException iioe) {
        method.abort();
        String msg = GERAL.OP_CANCELADA_USUARIO + TradAtualizadorDeVersoes.DIRECIONADO_A_APLICACAO;
        JOptionPane.showMessageDialog(down, msg);
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException ioe) {
            method.releaseConnection();
            System.exit(0);
        }
        if (downFile != null && downFile.exists()) {
            downFile.delete();
        }
        return false;
        //         System.err.println("Fatal transport error: " + iioe.getMessage());
        //         iioe.printStackTrace();
    } catch (IOException ioe) {
        log.error("Fatal transport error: " + ioe.getMessage(), ioe);
        return false;
    } finally {
        //Release the connection.
        method.releaseConnection();
    }
}

From source file:com.calclab.emite.j2se.services.HttpConnector.java

private Runnable createSendAction(final String httpBase, final String xml, final ConnectorCallback callback) {
    return new Runnable() {
        public void run() {
            final String id = HttpConnectorID.getNext();
            Logger.debug("Connector [{0}] send: {1}", id, xml);
            final HttpClientParams params = new HttpClientParams();
            params.setConnectionManagerTimeout(10000);
            final HttpClient client = new HttpClient(params);
            int status = 0;
            String response = null;
            final PostMethod post = new PostMethod(httpBase);

            try {
                post.setRequestEntity(new StringRequestEntity(xml, "text/xml", "utf-8"));
                System.out.println("SENDING: " + xml);
                status = client.executeMethod(post);
                response = post.getResponseBodyAsString();
            } catch (final Exception e) {
                callback.onError(xml, e);
                e.printStackTrace();//from   w w w.j  av  a2  s  .  c om
            } finally {
                post.releaseConnection();
            }

            receiveService.execute(createResponseAction(xml, callback, id, status, response));
        }
    };
}

From source file:com.mobilefirst.fiberlink.Authenticator.java

/**
  * Description: Create initial post method
  * @param xml: the xml body payload//from  w ww  .j  a  v  a  2 s .  c om
  * @param url_auth: URL to post
  * @param billing_id: the unique billing ID for the Fiberlink Customer
  * @return: PostMethod
  */
public void createAndSendRequest(String xml, String url_auth, String billing_id) {
    PostMethod post = new PostMethod(url_auth + billing_id + "/");
    try {
        RequestEntity requestEntity = new StringRequestEntity(xml, "application/xml", "UTF-8");
        post.setRequestEntity(requestEntity);
        post.addRequestHeader("Accept", "application/xml");
    } catch (Exception e) {
        e.printStackTrace();
    }

    sendRequest(post);
}

From source file:com.ohalo.baidu.map.BaiduMapTest.java

/**
 * /*from ww w .  jav a 2 s  .co m*/
 * <pre>
 * ??
 * 
 * 2013-10-8
 * </pre>
 * 
 * @throws IllegalArgumentException
 * @throws IOException
 */
public void testSearchCompanyDetailInfo() throws IllegalArgumentException, IOException {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod("http://www.sgs.gov.cn/lz/etpsInfo.do?method=viewDetail");
    method.setRequestBody(new NameValuePair[] { new NameValuePair("etpsId", "150000022004032200107") });
    client.executeMethod(method);
    String response = new String(method.getResponseBody());
    System.out.println(response);
}

From source file:com.zimbra.cs.dav.service.DavMethod.java

public HttpMethod toHttpMethod(DavContext ctxt, String targetUrl) throws IOException, DavException {
    if (ctxt.getUpload() != null && ctxt.getUpload().getSize() > 0) {
        PostMethod method = new PostMethod(targetUrl) {
            @Override//w  w  w.  j av a  2  s.  co m
            public String getName() {
                return getMethodName();
            }
        };
        RequestEntity reqEntry;
        if (ctxt.hasRequestMessage()) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLWriter writer = new XMLWriter(baos);
            writer.write(ctxt.getRequestMessage());
            reqEntry = new ByteArrayRequestEntity(baos.toByteArray());
        } else { // this could be a huge upload
            reqEntry = new InputStreamRequestEntity(ctxt.getUpload().getInputStream(),
                    ctxt.getUpload().getSize());
        }
        method.setRequestEntity(reqEntry);
        return method;
    }
    return new GetMethod(targetUrl) {
        @Override
        public String getName() {
            return getMethodName();
        }
    };
}

From source file:eu.learnpad.core.impl.qm.XwikiBridgeInterfaceRestResource.java

private String localGenerateQuestionnaires(String modelSetId, String type, byte[] configurationFile)
        throws LpRestExceptionXWikiImpl {
    // Ask the QM to generate new questionnaire for a given model set
    // that has been already imported
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/qm/bridge/generate/%s", DefaultRestResource.REST_URI, modelSetId);
    PostMethod postMethod = new PostMethod(uri);

    NameValuePair[] queryString = new NameValuePair[1];
    queryString[0] = new NameValuePair("type", type);
    postMethod.setQueryString(queryString);

    RequestEntity requestEntity = null;//from   w w w.j  ava  2s . c om
    if (configurationFile != null) {
        postMethod.addRequestHeader("Content-Type", "application/octet-stream");
        requestEntity = new ByteArrayRequestEntity(configurationFile);
    }
    postMethod.setRequestEntity(requestEntity);

    String genProcessID = null;
    try {
        httpClient.executeMethod(postMethod);
        genProcessID = postMethod.getResponseBodyAsString();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
    return genProcessID;
}

From source file:it.eng.spagobi.engines.talend.client.SpagoBITalendEngineClient.java

public static String getEngineComplianceVersion(String url)
        throws EngineUnavailableException, ServiceInvocationFailedException {
    String version;/*from   w w w . j a  v a 2  s .  c  o  m*/
    HttpClient client;
    PostMethod method;
    NameValuePair[] nameValuePairs;

    version = null;
    client = new HttpClient();
    method = new PostMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    nameValuePairs = new NameValuePair[] { new NameValuePair("infoType", "complianceVersion") }; //$NON-NLS-1$ //$NON-NLS-2$

    method.setRequestBody(nameValuePairs);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new ServiceInvocationFailedException(
                    Messages.getString("SpagoBITalendEngineClient.serviceFailed"), //$NON-NLS-1$
                    method.getStatusLine().toString(), method.getResponseBodyAsString());
        } else {
            version = method.getResponseBodyAsString();
        }

    } catch (HttpException e) {
        throw new EngineUnavailableException(Messages.getString("SpagoBITalendEngineClient.5", e.getMessage())); //$NON-NLS-1$
    } catch (IOException e) {
        throw new EngineUnavailableException(Messages.getString("SpagoBITalendEngineClient.6", e.getMessage())); //$NON-NLS-1$
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return version;
}

From source file:com.bdaum.juploadr.uploadapi.locrrest.upload.LocrUpload.java

@Override
public boolean execute() throws ProtocolException, CommunicationException {
    HttpClient httpClient = HttpClientFactory.getHttpClient(getSession().getAccount());

    // checkAuthorization(client);
    this.monitor.uploadStarted(new UploadEvent(image, 0, true, false));

    PostMethod post = new PostMethod(POSTURL);
    List<Part> parts = getParts();
    MultipartRequestEntity entity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]),
            post.getParams());/*from www .  ja  v  a  2  s.  co m*/
    post.setRequestEntity(entity);

    try {

        int status = httpClient.executeMethod(post);
        if (status == HttpStatus.SC_OK) {
            // deal with the response
            try {
                String response = post.getResponseBodyAsString();
                post.releaseConnection();
                boolean success = parseResponse(response);
                if (success) {
                    image.setState(UploadImage.STATE_UPLOADED);
                    ImageUploadResponse resp = new ImageUploadResponse(
                            ((LocrUploadResponseHandler) handler).getPhotoID());
                    this.monitor.uploadFinished(new UploadCompleteEvent(resp, image));

                } else {
                    throw new UploadFailedException(Messages.getString("juploadr.ui.error.status")); //$NON-NLS-1$
                }

            } catch (IOException e) {
                // TODO: Is it safe to assume the upload failed here?
                this.fail(Messages.getString("juploadr.ui.error.response.unreadable") //$NON-NLS-1$
                        + e.getMessage(), e);
            }
        } else {
            this.fail(Messages.getString("juploadr.ui.error.bad.http.response", status), null); //$NON-NLS-1$
        }
    } catch (ConnectException ce) {
        this.fail(Messages.getString("juploadr.ui.error.unable.to.connect"), ce); //$NON-NLS-1$
    } catch (NoRouteToHostException route) {
        this.fail(Messages.getString("juploadr.ui.error.no.internet"), route); //$NON-NLS-1$
    } catch (UnknownHostException uhe) {
        this.fail(Messages.getString("juploadr.ui.error.unknown.host"), uhe); //$NON-NLS-1$

    } catch (HttpException e) {
        this.fail(Messages.getString("juploadr.ui.error.http.exception") + e, e); //$NON-NLS-1$
    } catch (IOException e) {
        this.fail(Messages.getString("juploadr.ui.error.simple.ioexception") + e.getMessage() + "" //$NON-NLS-1$ //$NON-NLS-2$
                + e, e);
    }
    return true;
}