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:com.panet.imeta.trans.steps.httppost.HTTPPOST.java

private Object[] callHTTPPOST(Object[] rowData) throws KettleException {
    // get dynamic url ?
    if (meta.isUrlInField())
        data.realUrl = data.inputRowMeta.getString(rowData, data.indexOfUrlField);

    try {/*  w  w w  . j  a va 2s. com*/
        if (log.isDetailed())
            logDetailed(Messages.getString("HTTPPOST.Log.ConnectingToURL", data.realUrl));

        // Prepare HTTP POST
        // 
        HttpClient HTTPPOSTclient = new HttpClient();
        PostMethod post = new PostMethod(data.realUrl);
        //post.setFollowRedirects(false); 

        // Specify content type and encoding
        // If content encoding is not explicitly specified
        // ISO-8859-1 is assumed
        if (Const.isEmpty(data.realEncoding))
            post.setRequestHeader("Content-type", "text/xml");
        else
            post.setRequestHeader("Content-type", "text/xml; " + data.realEncoding);

        // BODY PARAMETERS
        if (data.useBodyParameters) {
            // set body parameters that we want to send 
            for (int i = 0; i < data.body_parameters_nrs.length; i++) {
                data.bodyParameters[i]
                        .setValue(data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i]));
            }
            post.setRequestBody(data.bodyParameters);
        }

        // QUERY PARAMETERS
        if (data.useQueryParameters) {
            for (int i = 0; i < data.query_parameters_nrs.length; i++) {
                data.queryParameters[i]
                        .setValue(data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i]));
            }
            post.setQueryString(data.queryParameters);
        }

        // Set request entity?
        if (data.indexOfRequestEntity >= 0) {
            String tmp = data.inputRowMeta.getString(rowData, data.indexOfRequestEntity);
            // Request content will be retrieved directly
            // from the input stream
            // Per default, the request content needs to be buffered
            // in order to determine its length.
            // Request body buffering can be avoided when
            // content length is explicitly specified

            if (meta.isPostAFile()) {
                File input = new File(tmp);
                post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
            } else {
                post.setRequestEntity(
                        new InputStreamRequestEntity(new ByteArrayInputStream(tmp.getBytes()), tmp.length()));
            }
        }

        // Execute request
        // 
        InputStream inputStream = null;
        try {
            // Execute the POST method
            int statusCode = HTTPPOSTclient.executeMethod(post);

            // Display status code
            if (log.isDebug())
                log.logDebug(toString(), Messages.getString("HTTPPOST.Log.ResponseCode", "" + statusCode));
            String body = null;
            if (statusCode != -1) {
                // the response
                inputStream = post.getResponseBodyAsStream();
                StringBuffer bodyBuffer = new StringBuffer();
                int c;
                while ((c = inputStream.read()) != -1)
                    bodyBuffer.append((char) c);
                inputStream.close();

                // Display response
                body = bodyBuffer.toString();

                if (log.isDebug())
                    log.logDebug(toString(), Messages.getString("HTTPPOST.Log.ResponseBody", body));
            }
            //return new Value(meta.getFieldName(), body);
            return RowDataUtil.addValueData(rowData, data.inputRowMeta.size(), body);
        } finally {
            if (inputStream != null)
                inputStream.close();
            // Release current connection to the connection pool once you are done
            post.releaseConnection();
        }
    } catch (Exception e) {
        throw new KettleException(Messages.getString("HTTPPOST.Error.CanNotReadURL", data.realUrl), e);

    }
}

From source file:net.navasoft.madcoin.backend.services.push.AndroidPushNotificationConfiguration.java

/**
 * Creates the service.//from  w w w .ja va  2  s . c om
 * 
 * @return the object
 * @throws PushNotificationException
 *             the push notification exception
 * @since 27/07/2014, 06:48:42 PM
 */
@Override
public Object createService() throws PushNotificationException {
    try {
        service = new HttpClient();
        PostMethod method = new PostMethod("https://www.google.com/accounts/ClientLogin");
        method.addParameter("Email", getUsername());
        method.addParameter("Passwd", getPassword());
        method.addParameter("accountType", "HOSTED_OR_GOOGLE");
        method.addParameter("source", "unit-test");
        method.addParameter("service", "ac2dm");
        service.executeMethod(method);
        byte[] responseBody = method.getResponseBody();
        String response = new String(responseBody);
        String auth = response.split("\n")[2];
        token = auth.split("=")[1];
        return service;
    } catch (HttpException e) {
        e.printStackTrace();
        throw new PushNotificationException("HTTP ", e);
    } catch (IOException e) {
        e.printStackTrace();
        throw new PushNotificationException("IO", e);
    }

}

From source file:at.ac.tuwien.auto.sewoa.http.HttpRetrieverImpl.java

public byte[] postData(String url, String data) {
    byte[] result = new byte[] {};
    HttpClient httpClient = httpClientFactory.createClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.setRequestEntity(new StringRequestEntity(data));

    HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams();
    params.setConnectionTimeout((int) TimeUnit.SECONDS.toMillis(CONNECTION_TO));
    params.setSoTimeout((int) TimeUnit.SECONDS.toMillis(SOCKET_TO));
    postMethod.addRequestHeader("Content-Type", "application/xml");
    postMethod.addRequestHeader("Accept", "application/xml");

    try {// w  ww.  j  a v  a 2  s .  c  o  m
        result = send(httpClient, postMethod);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

From source file:cz.muni.fi.pa165.creatures.rest.client.services.impl.RegionCRUDServiceImpl.java

@Override
public void create(RegionDTO dto) {
    PostMethod postMethod = new PostMethod(uri);
    StringWriter writer = new StringWriter();

    try {//from  w  w  w  .ja  va2 s . c om
        context.createMarshaller().marshal(regionMapping.DTOtoEntity(dto), writer);
    } catch (JAXBException ex) {
        logger.log(Level.INFO, "Unable to marshall RegionDTO {0}", dto);
        return;
    }

    RequestEntity entity = new InputStreamRequestEntity(new ByteArrayInputStream(writer.toString().getBytes()));
    postMethod.setRequestEntity(entity);
    CRUDServiceHelper.send(postMethod);
}

From source file:cz.muni.fi.pa165.creatures.rest.client.services.impl.WeaponCRUDServiceImpl.java

@Override
public void create(WeaponDTO dto) {
    PostMethod postMethod = new PostMethod(uri);
    StringWriter writer = new StringWriter();

    try {//from www .j  a  va 2s . com
        context.createMarshaller().marshal(weaponMapping.DTOtoEntity(dto), writer);
    } catch (JAXBException ex) {
        logger.log(Level.INFO, "Unable to marshall CreatureDTO {0}", dto);
        return;
    }

    RequestEntity entity = new InputStreamRequestEntity(new ByteArrayInputStream(writer.toString().getBytes()));
    postMethod.setRequestEntity(entity);
    CRUDServiceHelper.send(postMethod);
}

From source file:com.epam.wilma.gepard.test.helper.ResourceUploaderDecorator.java

/**
 * Upload any kind of resource file (classes, templates, and so on) into Wilma.
 * This upload method WILL accept failure in upload.
 *
 * @param url      the target url that receives the uploaded resource
 * @param fileName that should be uploaded
 * @return with response code/*from  ww  w  .j  a  v  a 2 s . c  om*/
 * @throws Exception in case of error
 */
public ResponseData uploadResourceWithExpectedError(final String url, final String fileName) throws Exception {
    ResponseData responseData;
    String responseMessage;
    int statusCode;

    HttpClient httpClient = new HttpClient();
    PostMethod httpPost = new PostMethod(url);
    try {
        String content = createRequest(fileName, httpPost);
        logResourceUploadRequestEvent(fileName, content, url);
        statusCode = httpClient.executeMethod(httpPost);
        responseMessage = createResponse(httpPost);
    } catch (IOException e) {
        throw new Exception("Error during Resource Upload", e);
    }
    responseData = new ResponseData(statusCode, responseMessage);
    ResponseHolder responseHolder = new ResponseHolder();
    responseHolder.setResponseCode(responseData.getResponseCode());
    responseHolder.setResponseMessage(responseData.getMessage());
    logResponseEvent(responseHolder);

    return responseData;
}

From source file:com.alta189.cyborg.commit.ShortUrlService.java

public static String shorten(String url, String keyword) {
    switch (service) {
    case BIT_LY://  w w w .  j  av  a 2s  .c  om
        HttpClient httpclient = new HttpClient();
        HttpMethod method = new GetMethod("http://api.bit.ly/shorten");
        method.setQueryString(
                new NameValuePair[] { new NameValuePair("longUrl", url), new NameValuePair("version", "2.0.1"),
                        new NameValuePair("login", user), new NameValuePair("apiKey", apiKey),
                        new NameValuePair("format", "xml"), new NameValuePair("history", "1") });
        try {
            httpclient.executeMethod(method);
            String responseXml = method.getResponseBodyAsString();
            String retVal = null;
            if (responseXml != null) {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                StringReader st = new StringReader(responseXml);
                Document d = db.parse(new InputSource(st));
                NodeList nl = d.getElementsByTagName("shortUrl");
                if (nl != null) {
                    Node n = nl.item(0);
                    retVal = n.getTextContent();
                }
            }

            return retVal;
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        return null;
    case SPOUT_IN:
        HttpClient client = new HttpClient();
        String result = null;
        client.getParams().setParameter("http.useragent", "Test Client");

        BufferedReader br = null;
        PostMethod pMethod = new PostMethod("http://spout.in/yourls-api.php");
        pMethod.addParameter("signature", apiKey);
        pMethod.addParameter("action", "shorturl");
        pMethod.addParameter("format", "simple");
        pMethod.addParameter("url", url);
        if (keyword != null) {
            pMethod.addParameter("keyword", keyword);
        }

        try {
            int returnCode = client.executeMethod(pMethod);

            if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
                System.err.println("The Post method is not implemented by this URI");
                pMethod.getResponseBodyAsString();
            } else {
                br = new BufferedReader(new InputStreamReader(pMethod.getResponseBodyAsStream()));
                String readLine;
                if (((readLine = br.readLine()) != null)) {
                    result = readLine;
                }
            }
        } catch (Exception e) {
            System.err.println(e);
        } finally {
            pMethod.releaseConnection();
            if (br != null) {
                try {
                    br.close();
                } catch (Exception fe) {
                    fe.printStackTrace();
                }
            }
        }
        return result;
    }
    return null;
}

From source file:de.linsin.alterego.notification.AppNotificationService.java

PostMethod setUp(String argTitle, String argMessage) {
    PostMethod method = new PostMethod(URL);
    method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

    method.addParameter(USER_CREDENTIALS, credentials);
    method.addParameter(NOTIFICATION_LONG_MESSAGE, argMessage);
    method.addParameter(NOTIFICATION_TITLE, argTitle);
    method.addParameter(MESSAGE_LEVEL, "2");
    return method;
}

From source file:com.epam.wilma.gepard.testclient.HttpPostRequestSender.java

/**
 * Sends a new HTTP request to a server through a proxy. Also logs request and response with gepard framework.
 *
 * @param tc                is the caller Test Case.
 * @param requestParameters a set of parameters that will set the content of the request
 *                          and specify the proxy it should go through
 * @return with Response Holder class.//from ww  w. ja  v a2s.com
 * @throws IOException                  in case error occurs
 * @throws ParserConfigurationException in case error occurs
 * @throws SAXException                 in case error occurs
 */
public ResponseHolder callWilmaTestServer(final WilmaTestCase tc, final RequestParameters requestParameters)
        throws IOException, ParserConfigurationException, SAXException {
    String responseCode;
    ResponseHolder responseMessage;

    HttpClient httpClient = new HttpClient();
    PostMethod httpPost = new PostMethod(requestParameters.getTestServerUrl());
    if (requestParameters.isUseProxy()) {
        httpClient.getHostConfiguration().setProxy(requestParameters.getWilmaHost(),
                requestParameters.getWilmaPort());
    }
    createRequest(requestParameters, httpPost);
    tc.logPostRequestEvent(requestParameters); //this dumps the request

    String sendBuffer;
    try {
        sendBuffer = tc.getTestClassExecutionData().getEnvironment().getProperty("http.socket.sendbuffer");
    } catch (NullPointerException e) {
        sendBuffer = DEFAULT_BUFFER_SIZE_STRING;
    }
    String receiveBuffer;
    try {
        receiveBuffer = tc.getTestClassExecutionData().getEnvironment()
                .getProperty("http.socket.receivebuffer");
    } catch (NullPointerException e) {
        receiveBuffer = DEFAULT_BUFFER_SIZE_STRING;
    }

    httpClient.getHttpConnectionManager().getParams().setSendBufferSize(Integer.valueOf(sendBuffer));
    httpClient.getHttpConnectionManager().getParams().setReceiveBufferSize(Integer.valueOf(receiveBuffer));
    int statusCode;
    statusCode = httpClient.executeMethod(httpPost);
    responseCode = "status code: " + statusCode + "\n";
    responseMessage = createResponse(httpPost);
    responseMessage.setResponseCode(responseCode);
    tc.setActualResponseCode(statusCode);
    Header contentTypeHeader = httpPost.getResponseHeader("Content-Type");
    if (contentTypeHeader != null) {
        tc.setActualResponseContentType(contentTypeHeader.getValue());
    }
    Header sequenceHeader = httpPost.getResponseHeader("Wilma-Sequence");
    if (sequenceHeader != null) {
        tc.setActualDialogDescriptor(sequenceHeader.getValue());
    }
    tc.logResponseEvent(responseMessage); //this dumps the response

    return responseMessage;
}

From source file:de.ingrid.iplug.dsc.utils.BwstrLocUtil.java

/**
 * Get the response from BwStrLoc using Referencesystem 4326 and distance 0.
 * //w w w.ja va  2s  .com
 * @param bwStrId
 * @param kmFrom
 * @param kmTo
 * @return
 */
public String getResponse(String bwStrId, String kmFrom, String kmTo) {
    String response = null;

    PostMethod post = new PostMethod(bwstrLocEndpoint);
    post.setParameter("Content-Type", "application/json");

    try {
        RequestEntity reqE = new StringRequestEntity(
                "{\"queries\":[{\"qid\":1,\"bwastrid\":\"" + bwStrId + "\",\"stationierung\":{\"km_von\":"
                        + kmFrom + ",\"km_bis\":" + kmTo
                        + ",\"offset\":0},\"spatialReference\":{\"wkid\":4326}}]}",
                "application/json", "UTF-8");
        post.setRequestEntity(reqE);
        int resp = getHttpClient().executeMethod(post);
        if (resp != 200) {
            throw new Exception("Invalid HTTP Response Code.: " + resp);
        }
        response = post.getResponseBodyAsString();
    } catch (Exception e) {
        log.error("Error getting response from BwStrLocator at: " + bwstrLocEndpoint);
    } finally {
        post.releaseConnection();
    }
    return response;
}