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

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

Introduction

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

Prototype

public GetMethod(String uri) 

Source Link

Usage

From source file:com.urswolfer.intellij.plugin.gerrit.rest.GerritApiUtil.java

@NotNull
private static HttpMethod doREST(@NotNull String host, @Nullable String login, @Nullable String password,
        @NotNull String path, @Nullable final String requestBody, final boolean post) throws IOException {
    HttpClient client = getHttpClient(login, password);
    String uri = host + path;//from w  w w  .j a va  2  s  .  c  o  m
    return SslSupport.getInstance().executeSelfSignedCertificateAwareRequest(client, uri,
            new ThrowableConvertor<String, HttpMethod, IOException>() {
                @Override
                public HttpMethod convert(String uri) throws IOException {
                    if (post) {
                        PostMethod method = new PostMethod(uri);
                        if (requestBody != null) {
                            method.setRequestEntity(
                                    new StringRequestEntity(requestBody, "application/json", "UTF-8"));
                        }
                        return method;
                    }
                    return new GetMethod(uri);
                }
            });
}

From source file:com.bluexml.xforms.demo.Util.java

/**
 * Calls the XForms webapp with initialization values.
 * /*ww  w . ja  va 2s  .c  om*/
 * @param alfrescohost
 *            the address (protocol, host name, port number) to the Alfresco instance, with NO
 *            trailing slash. e.g. http://www.bluexml.com/alfresco
 * @param xformshost
 *            the address (including context) of the xforms webapp host, with NO trailing slash.
 *            e.g: http://localhost:8081/myforms
 * @param formsproperties
 *            the path to the forms.properties file
 * @param redirectxml
 *            the path to the redirect.xml file
 * @return
 */
public static boolean initWebApp(String alfrescohost, String xformshost, String formsproperties,
        String redirectxml) {
    if (StringUtils.trimToNull(xformshost) == null) {
        return false;
    }
    String serviceURL = xformshost + "/xforms?init=true";

    serviceURL += "&alfrescoHost=" + alfrescohost;
    serviceURL += "&redirectXmlFile=" + redirectxml;
    serviceURL += "&formsPropertiesFile=" + formsproperties;

    GetMethod get = new GetMethod(serviceURL);
    HttpClient client = new HttpClient();
    try {
        client.executeMethod(get);
    } catch (HttpException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    String result;
    try {
        result = get.getResponseBodyAsString();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    if (result == null) {
        return false;
    }
    result = result.trim();
    return result.equals("success");
}

From source file:edu.harvard.iq.dvn.core.web.dataaccess.CensusAccessObject.java

public void open() throws IOException {

    StudyFile file = this.getFile();
    DataAccessRequest req = this.getRequest();

    if (req.getParameter("noVarHeader") != null) {
        this.setNoVarHeader(true);
    }//from   w w  w .j av  a 2  s. c  o m

    if (req.getParameter("vars") == null || req.getParameter("vars").equals("")) {
        throw new IOException("CensusAccess open called without the vars parameter. "
                + "Only subsetting calls are supported.");
    }

    String remoteFileUrl = file.getFileSystemLocation();
    remoteFileUrl = remoteFileUrl + "?vars=" + req.getParameter("vars");

    if (remoteFileUrl != null) {
        remoteFileUrl = remoteFileUrl.replaceAll(" ", "+");
        this.setRemoteUrl(remoteFileUrl);
    }

    Boolean zippedStream = false;

    GetMethod method = null;
    int status = 200;

    try {
        // No authentication is required for census.gov access
        method = new GetMethod(remoteFileUrl);

        // normally, the HTTP client follows redirects
        // automatically, so we need to explicitely tell it
        // not to:

        // method.setFollowRedirects(false); -- not necessary for census

        status = (new HttpClient()).executeMethod(method);

    } catch (IOException ex) {
        //if (method != null) {
        //    method.releaseConnection();
        //}
        status = 404;
    }

    this.setStatus(status);

    if (status != 200) {
        if (method != null) {
            method.releaseConnection();
        }

        throw new IOException("CensusAccess: HTTP access failed; status: " + status);
    }

    InputStream in = null;
    String[] valueTokens;

    try {
        in = method.getResponseBodyAsStream();
        CensusInputStream cin = new CensusInputStream(in);
        String[] requestedVariables = req.getParameter("vars").split(",", -2);
        cin.setRequestedVariables(requestedVariables);

        this.setInputStream(cin);

    } catch (IOException ex) {
        this.setStatus(404);
        String errorMessage = "I/O error has occured while attempting to retreive a Census data file: "
                + ex.getMessage()
                + ". Please try again later and if the problem persists, report it to your DVN technical support contact.";
        this.setErrorMessage(errorMessage);

        throw new IOException(
                "I/O error has occured while attempting to retreive a Census data file: " + ex.getMessage());
    }

    this.setResponseHeaders(method.getResponseHeaders());
    this.setHTTPMethod(method);

}

From source file:com.datatorrent.demos.samplestream.YahooFinanceCSVInputOperator.java

@Override
public void setup(OperatorContext context) {
    url = prepareURL();//from  w ww. java 2s .  c om
    client = new HttpClient();
    method = new GetMethod(url);
    DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy",
            CookiePolicy.BROWSER_COMPATIBILITY);
}

From source file:net.sourceforge.jwbf.actions.mw.queries.GetCategoryMembers.java

/**
 * generates the next MediaWiki-request (GetMethod) and adds it to msgs.
 *
 * @param categoryName   the title of the article,
 *                      may only be null if blcontinue is not null
 * /*from   w  ww  .  j a va 2  s  . c  o m*/
 * @param cmcontinue    the value for the blcontinue parameter,
 *                      null for the generation of the initial request
 */
protected final void generateFirstRequest(String categoryName) {
    this.categoryName = categoryName.replace(" ", "_");

    try {

        msgs.add(new GetMethod(r.first(categoryName)));

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

}

From source file:javaapplicationclientrest.ControllerCliente.java

public void getNoticia(String id) {
    GetMethod get = new GetMethod(String.format(Constants.GET_NOTICIA, id));
    try {/*from w ww  . j a  va 2s . co m*/
        http.executeMethod(get);
        System.out.println("status: " + get.getStatusText() + "\nTESTANDO" + get.getResponseBodyAsString());
    } catch (IOException ex) {
        try {
            System.out.println("status: " + get.getStatusText() + "\n" + get.getResponseBodyAsString());
        } catch (IOException ex1) {
            Logger.getLogger(ControllerCliente.class.getName()).log(Level.SEVERE, null, ex1);
        }
        Logger.getLogger(ControllerCliente.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

@Override
public IEventInstance readData() throws AdapterException {
    List<String> eventsList;
    try {//  ww  w  . jav  a 2  s  .co  m
        if (getMethod == null) {
            getMethod = new GetMethod(producerURL);
            this.getMethod.setRequestHeader("Content-type", contentType + "; charset=ISO-8859-1");

        }
        eventsList = RestClient.getEventsFromProducer(httpClient, getMethod, producerURL, contentType);

        //in this mode we assume the list will always contain a single event instance
        if (eventsList == null || eventsList.isEmpty())
            return null;

        String eventInstanceText = eventsList.iterator().next();
        if (eventInstanceText == null || eventInstanceText.equals(""))
            return null;

        //in case the event is given with new lines, we need to concatenate the lines
        StringBuffer fullEventData = new StringBuffer();
        Iterator<String> iterator = eventsList.iterator();
        while (iterator.hasNext()) {
            fullEventData.append(iterator.next());
        }
        IEventInstance eventInstance = textFormatter.parseText(fullEventData.toString());
        eventInstance.setDetectionTime(Calendar.getInstance().getTimeInMillis());
        return eventInstance;
    } catch (RESTException e) {
        getMethod.releaseConnection();
        getMethod = null;
        throw new AdapterException(e);
    }

}

From source file:net.sourceforge.jwbf.actions.mw.queries.GetImagelinkTitles.java

/**
 * generates the next MediaWiki-request (GetMethod) and adds it to msgs.
 *
 * @param imageName     the title of the image,
 *                      may only be null if ilcontinue is not null
 * @param namespace     the namespace(s) that will be searched for links,
 *                      as a string of numbers separated by '|';
 *                      if null, this parameter is omitted
 * @param ilcontinue    the value for the ilcontinue parameter,
 *                      null for the generation of the initial request
 *///  w  w  w . j a  v a2s  .com
protected void generateRequest(String imageName, String namespace, String ilcontinue) {

    String uS = "";

    try {

        if (ilcontinue == null) {

            uS = "/api.php?action=query&list=imageusage" + "&iutitle="
                    + URLEncoder.encode(imageName, MediaWikiBot.CHARSET)
                    + ((namespace != null && !namespace.isEmpty()) ? ("&ilnamespace=" + namespace) : "")
                    + "&illimit=" + LIMIT + "&format=xml";

        } else {

            uS = "/api.php?action=query&list=imageusage" + "&ilcontinue="
                    + URLEncoder.encode(ilcontinue, MediaWikiBot.CHARSET) + "&illimit=" + LIMIT + "&format=xml";

        }

        System.out.println(uS);

        msgs.add(new GetMethod(uS));

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

}

From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryClient.java

/**
 * Construct and select are sent across the wire in exactly the same way.
 *///w w w .j a va  2s. c om
private String executeQuery(final String query, final QueryLanguage ql, final boolean includeInferred)
        throws Exception {

    GetMethod get = new GetMethod(servletURL);
    // just to be nice.
    get.addRequestHeader(new Header("Accept", "application/rdf+xml"));
    // and say what we want.
    get.addRequestHeader(new Header("Accept-Charset", "UTF-8"));

    try {

        // add the range and include inferred headers
        get.addRequestHeader(
                new Header(GraphRepositoryServlet.X_INCLUDE_INFERRED, String.valueOf(includeInferred)));
        if (query != null) {
            // add the range header
            String range = ql.toString().toLowerCase() + "[" + trim(query) + "]";
            get.addRequestHeader(new Header(GraphRepositoryServlet.HTTP_RANGE, range));
        }

        // Execute the method.
        int sc = getHttpClient().executeMethod(get);
        if (sc != HttpStatus.SC_OK && sc != HttpStatus.SC_PARTIAL_CONTENT) {
            throw new IOException("HTTP-GET failed: " + get.getStatusLine());
        }

        // Read the response body.
        String response = IOUtils.readString(get.getResponseBodyAsStream(), get.getResponseCharSet());
        return response;

    } finally {
        // Release the connection.
        get.releaseConnection();
    }

}

From source file:edu.cmu.cs.diamond.pathfind.DjangoAnnotationStore.java

@Override
public SelectionListModel getAnnotations(String quickhash1) throws IOException {
    SelectionListModel ssModel = new DefaultSelectionListModel();

    try {/*from w w  w  .  j av a  2 s . co m*/
        URI u = new URI(uriPrefix + quickhash1 + "/");
        System.out.println(u);

        GetMethod g = new GetMethod(u.toString());
        try {
            InputStream in = getBody(g);
            if (in != null) {
                RegionList rl = JAXB.unmarshal(in, RegionList.class);

                // convert RegionList
                for (Region r : rl.getRegion()) {
                    Shape s = SlideAnnotation.stringToShape(r.getPath());
                    Integer id = r.getId();
                    String creator = r.getCreator();

                    List<SlideAnnotationNote> notes = new ArrayList<SlideAnnotationNote>();
                    for (Note n : r.getNotes().getNote()) {
                        SlideAnnotationNote san = new SlideAnnotationNote(n.getCreator(), n.getId(),
                                n.getText());
                        notes.add(san);
                    }

                    SlideAnnotation sa = new SlideAnnotation(s, id, creator, notes);
                    System.out.println(sa);
                    ssModel.add(sa);
                }
            }
        } finally {
            g.releaseConnection();
        }
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }

    return ssModel;
}