Example usage for org.apache.commons.httpclient HttpClient executeMethod

List of usage examples for org.apache.commons.httpclient HttpClient executeMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient executeMethod.

Prototype

public int executeMethod(HttpMethod paramHttpMethod) throws IOException, HttpException 

Source Link

Usage

From source file:de.mpg.imeji.presentation.util.SearchAndExportHelper.java

public static String getCitation(Publication publication) {
    URI uri = publication.getUri();
    URI searchAndExportUri = URI.create("http://" + uri.getHost() + "/search/SearchAndExport");
    String itemId = null;/*  w  ww  .  ja  va  2 s  . c  o  m*/
    if (uri.getQuery() != null && uri.getQuery().contains("itemId=")) {
        itemId = uri.getQuery().split("itemId=")[1];
    } else if (uri.getPath() != null && uri.getPath().contains("/item/")) {
        itemId = uri.getPath().split("/item/")[1];
    }
    if (UrlHelper.isValidURI(searchAndExportUri)) {
        try {
            HttpClient client = new HttpClient();
            String exportUri = searchAndExportUri.toString() + "?cqlQuery=" + URLEncoder.encode(
                    "escidoc.objid=" + itemId + " or escidoc.property.version.objid=" + itemId, "ISO-8859-1")
                    + "&exportFormat=" + publication.getExportFormat() + "&outputFormat=html_linked";
            GetMethod method = new GetMethod(exportUri);
            client.executeMethod(method);
            return method.getResponseBodyAsString();
        } catch (Exception e) {
            return null;
        }
    }
    return null;
}

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   ww w . jav  a  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.tribune.uiautomation.testscripts.Photo.java

public static Photo find(String namespace, String slug) throws JSONException {
    if (namespace == null || slug == null) {
        return null;
    }//from  www.j  a  v  a 2s . c  om
    GetMethod get = new GetMethod(constructResourceUrl(namespace, slug));
    setRequestHeaders(get);
    Photo photo = null;

    try {
        HttpClient client = new HttpClient();
        int status = client.executeMethod(get);

        log.debug("Photo Service find return status: " + get.getStatusLine());

        if (status == HttpStatus.SC_OK) {
            photo = new Photo();
            processResponse(photo, get.getResponseBodyAsStream());
            photo.setPersisted(true);
        }
    } catch (HttpException e) {
        log.fatal("Fatal protocol violation: " + e.getMessage(), e);
    } catch (IOException e) {
        log.fatal("Fatal transport error: " + e.getMessage(), e);
    } finally {
        // Release the connection.
        get.releaseConnection();
    }

    return photo;
}

From source file:com.mindquarry.desktop.util.HttpUtilities.java

private static GetMethod createAndExecuteGetMethod(String address, HttpClient client)
        throws IOException, HttpException {
    GetMethod get = new GetMethod(address);
    get.setDoAuthentication(true);/*from  w w w . j  a  v  a 2  s. c o m*/
    get.addRequestHeader("accept", "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$

    log.info("Executing HTTP GET on " + address); //$NON-NLS-1$
    client.executeMethod(get);
    log.info("Finished HTTP GET with status code: "//$NON-NLS-1$
            + get.getStatusCode());
    return get;
}

From source file:com.buglabs.dragonfly.util.WSHelper.java

protected static String get(String url, String token) throws IOException {
    HttpClient c = new HttpClient();

    GetMethod m = new GetMethod(url);
    m.setRequestHeader("Cookie", "token=" + token);

    c.executeMethod(m);

    return m.getResponseBodyAsString();
}

From source file:com.touch6.sm.gateway.webchinese.Webchinese.java

public static String batchSend(String url, String uid, String key, String phone, String msg, String contentType,
        String charset) throws CoreException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(url);
    post.addRequestHeader("Content-Type", contentType);//?
    NameValuePair[] data = { new NameValuePair("Uid", uid), new NameValuePair("Key", key),
            new NameValuePair("smsMob", phone), new NameValuePair("smsText", msg) };
    post.setRequestBody(data);/*from  w ww .j  a va  2  s  . co m*/
    try {
        client.executeMethod(post);
    } catch (Exception e) {
        logger.info("??:", e);
        throw new CoreException(ECodeUtil.getCommError(SystemErrorConstant.SYSTEM_EXCEPTION));
    }
    Header[] headers = post.getResponseHeaders();
    int statusCode = post.getStatusCode();
    System.out.println("statusCode:" + statusCode);
    for (Header h : headers) {
        System.out.println(h.toString());
    }
    String result;
    try {
        result = new String(post.getResponseBodyAsString().getBytes(charset));
        System.out.println(result); //???
    } catch (Exception e) {
        logger.info("??:", e);
        throw new CoreException(ECodeUtil.getCommError(SystemErrorConstant.SYSTEM_EXCEPTION));
    }

    post.releaseConnection();
    return result;
}

From source file:edu.pitt.dbmi.facebase.hd.HumanDataController.java

/** http web client class used for communicating with Hub 
 * @param action String is one of status, update, event
 * @param signal String is a timeInSeconds or QueueID or eventCode
 * for action=status, signal is "0", number-of-seconds-until-back, 
 * for action=update, signal is qid.hash
 * for action=event, signal "1" means mysql server is unavailable.
 * uses getOTP() method for URL construction
 *//* www . j  av a  2 s.  co  m*/
public static void httpGetter(String action, String signal) {
    String oneTimePassword = (new Long(getOTP())).toString();
    String url = hubURL + responseTrigger + oneTimePassword + "/";
    if (action == "update") {
        url += action + "/" + signal;
    } else if (action == "status") {
        long time = System.currentTimeMillis() / 1000L;
        time += Long.parseLong(signal);
        Long timeLong;
        timeLong = new Long(time);
        url += action + "/" + timeLong.toString();
    } else if (action == "event") {
        url += action + "/" + signal;
    } else {
    }
    HttpClient webClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(url);
    try {
        webClient.executeMethod(httpMethod);
        String response = httpMethod.getResponseBodyAsString();
    } catch (HttpException httpe) {
    } catch (IOException ioe) {
    } finally {
        httpMethod.releaseConnection();
        httpMethod.recycle();
    }
}

From source file:com.buglabs.dragonfly.util.WSHelper.java

/**
 * @param url/*w w w .  jav a2s  . co m*/
 * @param payload
 * @return
 * @throws HttpException
 * @throws IOException
 */
protected static String put(String url, String payload) throws HttpException, IOException {
    HttpClient c = new HttpClient();

    PutMethod m = new PutMethod(url);
    m.setRequestEntity(new StringRequestEntity(payload));
    c.executeMethod(m);

    return m.getResponseBodyAsString();
}

From source file:com.djimenez.tuenti.example.FormLoginDemo.java

/**
 * @param client/*  w ww  .  ja  v  a2s .  c o m*/
 * @param header
 * @throws IOException
 * @throws HttpException
 */
private static void checkHeader(final HttpClient client, final Header header) throws IOException {

    if (header != null) {
        String newuri = header.getValue();
        if ((newuri == null) || (newuri.equals(""))) {
            newuri = "/";
        }
        System.out.println("Redirect target: " + newuri);
        final GetMethod redirect = new GetMethod(newuri);

        client.executeMethod(redirect);
        System.out.println("Redirect: " + redirect.getStatusLine().toString());
        // release any connection resources used by the method
        redirect.releaseConnection();
    } else {
        System.out.println("Invalid redirect");
        System.exit(1);
    }
}

From source file:kevin.gvmsgarch.App.java

private static String getRnrse(String authToken) throws IOException {

    String retval = null;//from  w  w  w .  j a v a2 s.  c om
    HttpClient c = new HttpClient();
    GetMethod m = new GetMethod("https://www.google.com/voice/b/0");
    m.setRequestHeader("Authorization", "GoogleLogin auth=" + authToken);

    int rcode = -1;
    rcode = c.executeMethod(m);
    if (rcode != 200) {
        throw new RuntimeException("Received rcode: " + rcode);
    }
    retval = makeStringFromStream(m.getResponseBodyAsStream()).split("'_rnr_se':")[1].split("'")[1];
    return retval;
}