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:edu.stanford.epad.common.plugins.PluginFileUtil.java

public static int sendFileToRemoteEPAD(String username, String epadHost, String epadSessionID, String projectID,
        String subjectID, String studyUID, String seriesUID, File file, String description) throws Exception {
    String url = buildEPADBaseURL(epadHost, EPADConfig.epadPort,
            "/epad/v2/" + getAction(projectID, subjectID, studyUID, seriesUID, username));
    log.info("upload url " + url);
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    if (epadSessionID != null)
        postMethod.setRequestHeader("Cookie", "JSESSIONID=" + epadSessionID);
    try {//from  ww w  .  java  2 s.c o m
        Part[] parts = { new FilePart(file.getName(), file), new StringPart("description", description) };

        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

        return client.executeMethod(postMethod);
    } catch (Exception e) {
        log.warning("Exception calling ePAD", e);
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:com.pieframework.runtime.utils.CampfireNotifier.java

public static boolean notify(String msg, String url, String user, String password) {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(url);

    // stuff the Authorization request header
    byte[] encodedPassword = (user + ":" + password).getBytes();
    BASE64Encoder encoder = new BASE64Encoder();
    post.setRequestHeader("Authorization", "Basic " + encoder.encode(encodedPassword));

    try {//from  w w  w. jav a  2 s .c om
        RequestEntity entity = new StringRequestEntity("<message><body>" + msg + "</body></message>",
                "application/xml", "UTF-8");
        post.setRequestEntity(entity);
        client.executeMethod(post);
        String responseMsg = "httpStatus: " + post.getStatusCode() + " " + "Content-type: "
                + post.getResponseHeader("Content-Type") + " " + post.getResponseBodyAsString();
        Configuration.log().info(responseMsg);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return true;
}

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

/**
 * Put the specified event instance to the specified consumer.
 * The consumer is specified by the URL (which includes all the relevant info - the web
 * server name, port name, web service name and the URI path 
 * The content type can be either application/xml,application/json or plain text
 * The content type will be specified by the specific consumer, and a formatter
 * will be supplied to format the event instance to that type
 * /*from  w  w w  . j  ava  2s  .  com*/
 * @param url
 * @return
 * @throws AdapterException 
 * @throws RESTException 
 */
protected static void putEventToConsumer(String url, String eventInstance, String contentType, String authToken)
        throws RESTException {
    // Prepare HTTP PUT
    PostMethod postMethod = new PostMethod(url);

    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 POST of event instance: \n" + eventInstance
                        + "\nwith request headers:\n" + headers + "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
            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.zimbra.cs.servlet.ZimbraServlet.java

public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, Server server,
        String uri, AuthToken authToken) throws IOException, ServiceException {
    if (server == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "cannot find remote server");
        return;/*from   www  .ja va 2 s.c  o  m*/
    }
    HttpMethod method;
    String url = getProxyUrl(req, server, uri);
    mLog.debug("Proxy URL = %s", url);
    if (req.getMethod().equalsIgnoreCase("GET")) {
        method = new GetMethod(url.toString());
    } else if (req.getMethod().equalsIgnoreCase("POST") || req.getMethod().equalsIgnoreCase("PUT")) {
        PostMethod post = new PostMethod(url.toString());
        post.setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
        method = post;
    } else {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "cannot proxy method: " + req.getMethod());
        return;
    }
    HttpState state = new HttpState();
    String hostname = method.getURI().getHost();
    if (authToken != null) {
        authToken.encode(state, false, hostname);
    }
    try {
        proxyServletRequest(req, resp, method, state);
    } finally {
        method.releaseConnection();
    }
}

From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java

public static void executeDDL(String str) throws Exception {
    final String url = "http://localhost:19002/ddl";

    // Create a method instance.
    PostMethod method = new PostMethod(url);
    method.setRequestEntity(new StringRequestEntity(str));
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    executeHttpMethod(method);//from  ww  w .j ava 2  s.c o m
}

From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java

public static void executeUpdate(String str) throws Exception {
    final String url = "http://localhost:19002/update";

    // Create a method instance.
    PostMethod method = new PostMethod(url);
    method.setRequestEntity(new StringRequestEntity(str));

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

    // Execute the method.
    executeHttpMethod(method);//from  w  ww  .  j  a  va2 s  .  c  o m
}

From source file:gov.loc.ndmso.proxyfilter.RequestProxy.java

private static HttpMethod setupProxyRequest(final HttpServletRequest hsRequest, final URL targetUrl)
        throws IOException {
    final String methodName = hsRequest.getMethod();
    final HttpMethod method;
    if ("POST".equalsIgnoreCase(methodName)) {
        PostMethod postMethod = new PostMethod();
        InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(
                hsRequest.getInputStream());
        postMethod.setRequestEntity(inputStreamRequestEntity);
        method = postMethod;//from  ww  w.  j  av  a2  s  .  co  m
    } else if ("GET".equalsIgnoreCase(methodName)) {
        method = new GetMethod();
    } else {
        // log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod());
        return null;
    }

    method.setFollowRedirects(false);
    method.setPath(targetUrl.getPath());
    method.setQueryString(targetUrl.getQuery());

    @SuppressWarnings("unchecked")
    Enumeration<String> e = hsRequest.getHeaderNames();
    if (e != null) {
        while (e.hasMoreElements()) {
            String headerName = e.nextElement();
            if ("host".equalsIgnoreCase(headerName)) {
                //the host value is set by the http client
                continue;
            } else if ("content-length".equalsIgnoreCase(headerName)) {
                //the content-length is managed by the http client
                continue;
            } else if ("accept-encoding".equalsIgnoreCase(headerName)) {
                //the accepted encoding should only be those accepted by the http client.
                //The response stream should (afaik) be deflated. If our http client does not support
                //gzip then the response can not be unzipped and is delivered wrong.
                continue;
            } else if (headerName.toLowerCase().startsWith("cookie")) {
                //fixme : don't set any cookies in the proxied request, this needs a cleaner solution
                continue;
            }

            @SuppressWarnings("unchecked")
            Enumeration<String> values = hsRequest.getHeaders(headerName);
            while (values.hasMoreElements()) {
                String headerValue = values.nextElement();
                // log.info("setting proxy request parameter:" + headerName + ", value: " + headerValue);
                method.addRequestHeader(headerName, headerValue);
            }
        }
    }

    // add rs5/tomcat5 request header for ML
    method.addRequestHeader("X-Via", "tomcat5");

    // log.info("proxy query string " + method.getQueryString());
    return method;
}

From source file:com.linkedin.pinot.common.utils.FileUploadUtils.java

public static int sendSegmentJson(final String host, final String port, final JSONObject segmentJson) {
    PostMethod postMethod = null;
    try {/*from  w  w  w  . j a  v  a2 s. co m*/
        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();
        }
    }
}

From source file:at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient.java

private static Element sendSOAPRequest(String webServiceURL, Element request) throws MISSimpleClientException {

    //      try {
    //         System.out.println("REQUEST-MIS: \n"  + DOMUtils.serializeNode(request));
    //      } catch (TransformerException e1) {
    //         e1.printStackTrace();
    //      } catch (IOException e1) {
    //         e1.printStackTrace();
    //      }//w ww  .  ja va2 s. c om

    if (webServiceURL == null) {
        throw new NullPointerException("Argument webServiceURL must not be null.");
    }
    if (request == null) {
        throw new NullPointerException("Argument request must not be null.");
    }
    try {
        HttpClient httpclient = HttpClientWithProxySupport.getHttpClient();
        PostMethod post = new PostMethod(webServiceURL);
        StringRequestEntity re = new StringRequestEntity(DOMUtils.serializeNode(packIntoSOAP(request)),
                "text/xml", "UTF-8");
        post.setRequestEntity(re);
        int responseCode = httpclient.executeMethod(post);

        if (responseCode != 200) {
            throw new MISSimpleClientException("Invalid HTTP response code " + responseCode);
        }
        //Element elem = parse(post.getResponseBodyAsStream());
        Document doc = DOMUtils.parseDocumentSimple(post.getResponseBodyAsStream());
        return unpackFromSOAP(doc.getDocumentElement());

    } catch (IOException e) {
        throw new MISSimpleClientException("service.04", e);

    } catch (TransformerException e) {
        throw new MISSimpleClientException("service.06", e);

    } catch (SAXException e) {
        throw new MISSimpleClientException("service.06", e);

    } catch (ParserConfigurationException e) {
        throw new MISSimpleClientException("service.06", e);

    } catch (Exception e) {
        throw new MISSimpleClientException("service.06", e);

    }

}

From source file:gov.tva.sparky.util.indexer.HBaseRestInterface.java

public static void InsertDataIntoHBase(String str_REST_URL, byte[] arPayloadBytes) {

    BufferedReader br = null;/*ww  w  . j  a v  a2 s  .c o  m*/
    HttpClient client = new HttpClient();

    PostMethod post = new PostMethod(str_REST_URL);

    post.addRequestHeader("Content-Type", "application/octet-stream");
    RequestEntity entity = new ByteArrayRequestEntity(arPayloadBytes);
    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);
            }

        }

    } catch (Exception e) {

        System.out.println(e);

    } finally {

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

    }

}