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

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

Introduction

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

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:gov.tva.sparky.hbase.RestProxy.java

/**
 * This method adds data to HBase.//  www.ja  v a2s  .c  om
 * 
 * @param strTablename
 * @param strRowKey
 * @param strColumn
 * @param strQualifier
 * @param arBytesValue
 * @return
 * @throws URIException
 */
public static boolean InsertHbaseIndexBucket(String strTablename, String strRowKey, String strColumn,
        String strQualifier, byte[] arBytesValue) throws URIException {
    // Configuration
    Configuration conf = new Configuration(false);
    conf.addResource("hadoop-default.xml");
    conf.addResource("sparky-site.xml");
    int port = conf.getInt("sparky.hbase.restPort", 8092);
    String uri = conf.get("sparky.hbase.restURI", "http://socdvmhbase");

    boolean bResult = false;

    BufferedReader br = null;
    HttpClient client = new HttpClient();

    String strRestPath = uri + ":" + port + "/" + strTablename + "/" + strRowKey + "/" + strColumn + ":"
            + strQualifier;

    PostMethod post = new PostMethod(strRestPath);
    post.addRequestHeader("Content-Type", "application/octet-stream");

    RequestEntity entity = new ByteArrayRequestEntity(arBytesValue);
    post.setRequestEntity(entity);

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

        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.out.println("The Post method is not implemented by this URI");
            // still consume the response body
            post.getResponseBodyAsString();
        } else {
            br = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));
            String readLine;
            while (((readLine = br.readLine()) != null)) {
                System.out.println(readLine);
            }

            bResult = true;

        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
        if (br != null) {
            try {
                br.close();
            } catch (Exception fe) {
                fe.printStackTrace();
            }
        }
    }

    return bResult;
}

From source file:com.ibm.hrl.proton.adapters.rest.client.RestClient.java

protected static void patchEventToConsumer(String url, String urlExtension, String eventInstance,
        String contentType, String authToken) throws RESTException {
    // Prepare HTTP PUT
    String consumer = url + "/" + urlExtension;

    PostMethod postMethod = new PostMethod(consumer) {
        @Override/*from   w  ww  .  java 2 s .c  o  m*/
        public String getName() {
            return "PATCH";
        }
    };

    if (eventInstance != null) {

        RequestEntity requestEntity = new ByteArrayRequestEntity(eventInstance.getBytes());
        postMethod.setRequestEntity(requestEntity);

        // Specify content type and encoding
        // If content encoding is not explicitly specified
        // ISO-8859-1 is assumed
        // postMethod.setRequestHeader("Content-Type", contentType+"; charset=ISO-8859-1");
        postMethod.setRequestHeader("Content-Type", contentType);

        if (null != authToken && !authToken.isEmpty()) {
            postMethod.setRequestHeader("X-Auth-Token", authToken);
        }

        // Get HTTP client
        HttpClient httpclient = new HttpClient();

        // Execute request
        try {

            int result = httpclient.executeMethod(postMethod);

            if (result < 200 || result >= 300) {
                Header[] reqHeaders = postMethod.getRequestHeaders();
                StringBuffer headers = new StringBuffer();
                for (int i = 0; i < reqHeaders.length; i++) {
                    headers.append(reqHeaders[i].toString());
                    headers.append("\n");
                }
                throw new RESTException("Could not perform PATCH of event instance: \n" + eventInstance
                        + "\nwith request headers:\n" + headers + "to consumer " + consumer
                        + ", responce result: " + result);
            }

        } catch (Exception e) {
            throw new RESTException(e);
        } finally {
            // Release current connection to the connection pool 
            // once you are done
            postMethod.releaseConnection();
        }
    } else {
        System.out.println("Invalid request");
    }
    //        PutMethod putMethod = new PutMethod(url);        
    // 
    //        if(eventInstance != null) {
    //           RequestEntity requestEntity = new ByteArrayRequestEntity(eventInstance.getBytes());
    //           putMethod.setRequestEntity(requestEntity);
    //
    //        
    //           // Specify content type and encoding
    //           // If content encoding is not explicitly specified
    //           // ISO-8859-1 is assumed
    //           putMethod.setRequestHeader(
    //                   "Content-type", contentType+"; charset=ISO-8859-1");
    //           
    //           // Get HTTP client
    //           HttpClient httpclient = new HttpClient();
    //           
    //           // Execute request
    //           try {
    //               
    //               int result = httpclient.executeMethod(putMethod);
    //                              
    //               if (result < 200 || result >= 300)
    //               {
    //                  throw new RESTException("Could not perform PUT of event instance "+eventInstance+" to consumer "+ url+", responce result: "+result);
    //               }
    //              
    //           } catch(Exception e)
    //           {
    //              throw new RESTException(e);
    //           }
    //           finally {
    //               // Release current connection to the connection pool 
    //               // once you are done
    //               putMethod.releaseConnection();
    //           }
    //        } else
    //        {
    //           System.out.println ("Invalid request");
    //        }

}

From source file:com.mycompany.neo4jprotein.neoStart.java

static public String createNode() {
    String output = null;// www .j a  v  a2  s  .c o m
    String location = null;
    try {
        String nodePointUrl = SERVER_ROOT_URI + "/db/data/node/1";
        HttpClient client = new HttpClient();
        PostMethod mPost = new PostMethod(nodePointUrl);

        /**
         * set headers
         */
        Header mtHeader = new Header();
        mtHeader.setName("content-type");
        mtHeader.setValue("application/json");
        mtHeader.setName("accept");
        mtHeader.setValue("application/json");
        mPost.addRequestHeader(mtHeader);

        /**
         * set json payload
         */
        StringRequestEntity requestEntity = new StringRequestEntity("{}", "application/json", "UTF-8");
        mPost.setRequestEntity(requestEntity);
        int satus = client.executeMethod(mPost);
        output = mPost.getResponseBodyAsString();
        Header locationHeader = mPost.getResponseHeader("location");
        location = locationHeader.getValue();
        mPost.releaseConnection();
        System.out.println("satus : " + satus);
        System.out.println("location : " + location);
        System.out.println("output : " + output);
    } catch (Exception e) {
        System.out.println("Exception in creating node in neo4j : " + e);
    }

    return location;
}

From source file:eu.crowdrec.contest.sender.RequestSenderORP.java

/**
 * Send a line from a logFile to an HTTP server.
 * /*ww  w .  java  2  s  . c  o  m*/
 * @param logline the line that should by sent
 * 
 * @param connection the connection to the http server, must not be null
 * 
 * @return the response or null (if an error has been detected)
 */
static private String excutePostWithHttpClient(final String type, final String body, final String serverURL) {

    // define the URL parameter
    String urlParameters = "";

    try {

        urlParameters = String.format("type=%s&body=%s", URLEncoder.encode(type, "UTF-8"),
                URLEncoder.encode(body, "UTF-8"));

    } catch (UnsupportedEncodingException e1) {
        logger.warn(e1.toString());
    }

    PostMethod postMethod = null;
    try {
        StringRequestEntity requestEntity = new StringRequestEntity(urlParameters,
                "application/x-www-form-urlencoded", "UTF-8");

        postMethod = new PostMethod(serverURL);
        postMethod.setParameter("useCache", "false");
        postMethod.setRequestEntity(requestEntity);

        int statusCode = httpClient.executeMethod(postMethod);
        String response = statusCode == 200 ? postMethod.getResponseBodyAsString() : "statusCode:" + statusCode;

        return response.trim();
    } catch (IOException e) {
        logger.warn("receiving response failed, ignored.");
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
    return null;
}

From source file:ke.go.moh.oec.adt.Daemon.java

private static boolean sendMessage(String url, String filename) {
    int returnStatus = HttpStatus.SC_CREATED;
    HttpClient httpclient = new HttpClient();
    HttpConnectionManager connectionManager = httpclient.getHttpConnectionManager();
    connectionManager.getParams().setSoTimeout(120000);

    PostMethod httpPost = new PostMethod(url);

    RequestEntity requestEntity;//from   ww w . j a va2s .  c om
    try {
        FileInputStream message = new FileInputStream(filename);
        Base64InputStream message64 = new Base64InputStream(message, true, -1, null);
        requestEntity = new InputStreamRequestEntity(message64, "application/octet-stream");
    } catch (FileNotFoundException e) {
        Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "File not found.", e);
        return false;
    }
    httpPost.setRequestEntity(requestEntity);
    try {
        httpclient.executeMethod(httpPost);
        returnStatus = httpPost.getStatusCode();
    } catch (SocketTimeoutException e) {
        returnStatus = HttpStatus.SC_REQUEST_TIMEOUT;
        Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Request timed out.  Not retrying.", e);
    } catch (HttpException e) {
        returnStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "HTTP exception.  Not retrying.", e);
    } catch (ConnectException e) {
        returnStatus = HttpStatus.SC_SERVICE_UNAVAILABLE;
        Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Service unavailable.  Not retrying.", e);
    } catch (UnknownHostException e) {
        returnStatus = HttpStatus.SC_NOT_FOUND;
        Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Not found.  Not retrying.", e);
    } catch (IOException e) {
        returnStatus = HttpStatus.SC_GATEWAY_TIMEOUT;
        Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "IO exception.  Not retrying.", e);
    } finally {
        httpPost.releaseConnection();
    }
    return returnStatus == HttpStatus.SC_OK;
}

From source file:com.sun.faban.harness.webclient.ResultAction.java

/**
 * This method is responsible for uploading the runs to repository.
 * @param uploadSet//from   w w  w  .  j  a  v  a2  s  .  co  m
 * @param replaceSet
 * @return HashSet
 * @throws java.io.IOException
 */
public static HashSet<String> uploadRuns(String[] runIds, HashSet<File> uploadSet, HashSet<String> replaceSet)
        throws IOException {
    // 3. Upload the run
    HashSet<String> duplicates = new HashSet<String>();

    // Prepare run id set for cross checking.
    HashSet<String> runIdSet = new HashSet<String>(runIds.length);
    for (String runId : runIds) {
        runIdSet.add(runId);
    }

    // Prepare the parts for the request.
    ArrayList<Part> params = new ArrayList<Part>();
    params.add(new StringPart("host", Config.FABAN_HOST));
    for (String replaceId : replaceSet) {
        params.add(new StringPart("replace", replaceId));
    }
    for (File jarFile : uploadSet) {
        params.add(new FilePart("jarfile", jarFile));
    }
    Part[] parts = new Part[params.size()];
    parts = params.toArray(parts);

    // Send the request for each reposotory.
    for (URL repository : Config.repositoryURLs) {
        URL repos = new URL(repository, "/controller/uploader/upload_runs");
        PostMethod post = new PostMethod(repos.toString());
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_FORBIDDEN)
            logger.warning("Server denied permission to upload run !");
        else if (status == HttpStatus.SC_NOT_ACCEPTABLE)
            logger.warning("Run origin error!");
        else if (status != HttpStatus.SC_CREATED)
            logger.warning(
                    "Server responded with status code " + status + ". Status code 201 (SC_CREATED) expected.");
        for (File jarFile : uploadSet) {
            jarFile.delete();
        }

        String response = post.getResponseBodyAsString();

        if (status == HttpStatus.SC_CREATED) {

            StringTokenizer t = new StringTokenizer(response.trim(), "\n");
            while (t.hasMoreTokens()) {
                String duplicateRun = t.nextToken().trim();
                if (duplicateRun.length() > 0)
                    duplicates.add(duplicateRun.trim());
            }

            for (Iterator<String> iter = duplicates.iterator(); iter.hasNext();) {
                String runId = iter.next();
                if (!runIdSet.contains(runId)) {
                    logger.warning("Unexpected archive response from " + repos + ": " + runId);
                    iter.remove();
                }
            }
        } else {
            logger.warning("Message from repository: " + response);
        }
    }
    return duplicates;
}

From source file:com.comcast.cats.service.util.HttpClientUtil.java

public static synchronized Object postForObject(String requestUrl, byte[] payload) {
    Object responseObject = new Object();

    PostMethod httpMethod = new PostMethod(requestUrl);

    InputStream responseStream = null;
    Reader inputStreamReader = null;

    httpMethod.addRequestHeader(VideoRecorderServiceConstants.CONTENT_TYPE,
            VideoRecorderServiceConstants.APPLICATION_XML);

    RequestEntity requestEntity = new ByteArrayRequestEntity(payload, VideoRecorderServiceConstants.UTF);
    httpMethod.setRequestEntity(requestEntity);

    try {/* w w  w.  j a va  2s . co  m*/
        int responseCode = new HttpClient().executeMethod(httpMethod);

        if (HttpStatus.SC_OK != responseCode) {
            logger.error("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.error("[ METHOD   ] " + httpMethod.getName());
            logger.error("[ STATUS   ] " + responseCode);
        } else {
            logger.trace("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.trace("[ METHOD   ] " + httpMethod.getName());
            logger.trace("[ STATUS   ] " + responseCode);
        }

        responseStream = httpMethod.getResponseBodyAsStream();
        inputStreamReader = new InputStreamReader(responseStream, VideoRecorderServiceConstants.UTF);
        responseObject = new Yaml().load(inputStreamReader);
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        cleanUp(inputStreamReader, responseStream, httpMethod);
    }

    return responseObject;
}

From source file:eu.crowdrec.contest.sender.RequestSender.java

/**
 * Send a line from a logFile to an HTTP server.
 * //from ww  w.j av  a 2s  .c om
 * @param logline the line that should by sent
 * 
 * @param connection the connection to the http server, must not be null
 * 
 * @return the response or null (if an error has been detected)
 */
static private String excutePostWithHttpClient(final String logline, final String serverURL) {

    // split the logLine into several token
    String[] token = logline.split("\t");

    // define the URL parameter
    String urlParameters = "";

    boolean oldMethod = token.length < 4;
    if (oldMethod) {
        try {
            String type = logline.contains("\"event_type\": \"recommendation_request\"")
                    ? "recommendation_request"
                    : "event_notification";
            String newLine = logline.substring(0, logline.length() - 1)
                    + ", \"limit\":6, \"type\":\"impression\"}";
            urlParameters = String.format("type=%s&body=%s", URLEncoder.encode(type, "UTF-8"),
                    URLEncoder.encode(newLine, "UTF-8"));

        } catch (UnsupportedEncodingException e1) {
            logger.warn(e1.toString());
        }
    } else {
        String type = token[0];
        String property = token[3];
        String entity = token[4];

        // encode the content as URL parameters.
        try {
            urlParameters = String.format("type=%s&properties=%s&entities=%s", URLEncoder.encode(type, "UTF-8"),
                    URLEncoder.encode(property, "UTF-8"), URLEncoder.encode(entity, "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            logger.warn(e1.toString());
        }
    }

    PostMethod postMethod = null;
    try {
        StringRequestEntity requestEntity = new StringRequestEntity(urlParameters,
                "application/x-www-form-urlencoded", "UTF-8");

        postMethod = new PostMethod(serverURL);
        postMethod.setParameter("useCache", "false");
        postMethod.setRequestEntity(requestEntity);

        int statusCode = httpClient.executeMethod(postMethod);
        String response = statusCode == 200 ? postMethod.getResponseBodyAsString() : "statusCode:" + statusCode;

        return response.trim();
    } catch (IOException e) {
        logger.warn("receivind response failed, ignored.");
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
    return null;
}

From source file:fedora.test.api.TestHTTPStatusCodes.java

private static int getUploadCode(FedoraClient client, String url, File file, String partName) throws Exception {
    PostMethod post = null;
    try {//ww w. j av a 2 s .c om
        post = new PostMethod(url);
        post.setDoAuthentication(true);
        post.getParams().setParameter("Connection", "Keep-Alive");
        post.setContentChunked(true);
        Part[] parts = { new FilePart(partName, file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        int responseCode = client.getHttpClient().executeMethod(post);
        if (responseCode > 299 && responseCode < 400) {
            String location = post.getResponseHeader("location").getValue();
            System.out.println("Redirected to " + location);
            return getUploadCode(client, location, file, partName);
        } else {
            return responseCode;
        }
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java

/**
 *
 * @param endpoint/*from  ww w  . j av  a2s.  c  o m*/
 *            the url to the service to call
 * @param xml
 *            the BioMOBY input message
 * @return EndpointReference the EPR returned by the service
 * @throws MobyException
 */
private static EndpointReference launchCgiAsyncService(String endpoint, String xml) throws MobyException {
    // construct the Httpclient
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "jMoby/Taverna2");
    // create the post method
    PostMethod method = new PostMethod(endpoint);

    // put our data in the request
    RequestEntity entity;
    try {
        entity = new StringRequestEntity(xml, "text/xml", null);
    } catch (UnsupportedEncodingException e) {
        throw new MobyException("Problem posting data to webservice", e);
    }
    method.setRequestEntity(entity);

    // retry up to 10 times
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(10, true));

    // call the method
    try {
        int result = client.executeMethod(method);
        if (result != HttpStatus.SC_OK)
            throw new MobyException(
                    "Async HTTP POST service returned code: " + result + "\n" + method.getStatusLine());
        return EndpointReference.createFromXML(method.getResponseHeader("moby-wsrf").getValue());
    } catch (IOException e) {
        throw new MobyException("Problem reading response from webservice", e);
    } finally {
        // Release current connection to the connection pool once you are
        // done
        method.releaseConnection();
    }
}