Example usage for org.apache.commons.httpclient HttpMethod getQueryString

List of usage examples for org.apache.commons.httpclient HttpMethod getQueryString

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getQueryString.

Prototype

public abstract String getQueryString();

Source Link

Usage

From source file:TrivialApp.java

public static void main(String[] args) {
    if ((args.length != 1) && (args.length != 3)) {
        printUsage();/*from w  w w  .j a  v a  2  s .  c om*/
        System.exit(-1);
    }

    Credentials creds = null;
    if (args.length >= 3) {
        creds = new UsernamePasswordCredentials(args[1], args[2]);
    }

    //create a singular HttpClient object
    HttpClient client = new HttpClient();

    //establish a connection within 5 seconds
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    //set the default credentials
    if (creds != null) {
        client.getState().setCredentials(AuthScope.ANY, creds);
    }

    String url = args[0];
    HttpMethod method = null;

    //create a method object
    method = new GetMethod(url);
    method.setFollowRedirects(true);
    //} catch (MalformedURLException murle) {
    //    System.out.println("<url> argument '" + url
    //            + "' is not a valid URL");
    //    System.exit(-2);
    //}

    //execute the method
    String responseBody = null;
    try {
        client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());
        System.exit(-4);
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");
        System.exit(-3);
    }

    //write out the request headers
    System.out.println("*** Request ***");
    System.out.println("Request Path: " + method.getPath());
    System.out.println("Request Query: " + method.getQueryString());
    Header[] requestHeaders = method.getRequestHeaders();
    for (int i = 0; i < requestHeaders.length; i++) {
        System.out.print(requestHeaders[i]);
    }

    //write out the response headers
    System.out.println("*** Response ***");
    System.out.println("Status Line: " + method.getStatusLine());
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        System.out.print(responseHeaders[i]);
    }

    //write out the response body
    System.out.println("*** Response Body ***");
    System.out.println(responseBody);

    //clean up the connection resources
    method.releaseConnection();

    System.exit(0);
}

From source file:ExampleP2PHttpClient.java

public static void main(String[] args) {
    // initialize JXTA
    try {//from   w w  w  .j a  va 2 s  .com
        // sign in and initialize the JXTA network; profile this peer and create it
        // if it doesn't exist
        P2PNetwork.signin("clientpeer", "clientpeerpassword", "TestNetwork", true);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    // register the P2P socket protocol factory
    Protocol jxtaHttp = new Protocol("p2phttp", new P2PProtocolSocketFactory(), 80);
    Protocol.registerProtocol("p2phttp", jxtaHttp);

    //create a singular HttpClient object
    HttpClient client = new HttpClient();

    //establish a connection within 50 seconds
    client.setConnectionTimeout(50000);

    String url = System.getProperty("url");
    if (url == null || url.equals("")) {
        System.out.println("You must provide a URL to access.  For example:");
        System.out.println("ant example-webclient-run -D--url=p2phttp://www.somedomain.foo");

        System.exit(1);
    }
    System.out.println("Connecting to " + url + "...");

    HttpMethod method = null;

    //create a method object
    method = new GetMethod(url);
    method.setFollowRedirects(true);
    method.setStrictMode(false);
    //} catch (MalformedURLException murle) {
    //    System.out.println("<url> argument '" + url
    //            + "' is not a valid URL");
    //    System.exit(-2);
    //}

    //execute the method
    String responseBody = null;
    try {
        client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());
        System.exit(-4);
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");
        System.exit(-3);
    }

    //write out the request headers
    System.out.println("*** Request ***");
    System.out.println("Request Path: " + method.getPath());
    System.out.println("Request Query: " + method.getQueryString());
    Header[] requestHeaders = method.getRequestHeaders();
    for (int i = 0; i < requestHeaders.length; i++) {
        System.out.print(requestHeaders[i]);
    }

    //write out the response headers
    System.out.println("*** Response ***");
    System.out.println("Status Line: " + method.getStatusLine());
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        System.out.print(responseHeaders[i]);
    }

    //write out the response body
    System.out.println("*** Response Body ***");
    System.out.println(responseBody);

    //clean up the connection resources
    method.releaseConnection();
    method.recycle();

    System.exit(0);
}

From source file:lucee.commons.net.http.httpclient3.HttpMethodCloner.java

/**
* Clones a HttpMethod. &ltbr>/*from   w  ww  .  ja va  2s  .  c  o m*/
* &ltb&gtAttention:</b> You have to clone a method before it has
* been executed, because the URI can change if followRedirects
* is set to true.
*
* @param m the HttpMethod to clone
*
* @return the cloned HttpMethod, null if the HttpMethod could
* not be instantiated
*
* @throws java.io.IOException if the request body couldn't be read
*/
public static HttpMethod clone(HttpMethod m) {
    HttpMethod copy = null;
    try {
        copy = m.getClass().newInstance();
    } catch (InstantiationException iEx) {
    } catch (IllegalAccessException iaEx) {
    }
    if (copy == null) {
        return null;
    }
    copy.setDoAuthentication(m.getDoAuthentication());
    copy.setFollowRedirects(m.getFollowRedirects());
    copy.setPath(m.getPath());
    copy.setQueryString(m.getQueryString());

    Header[] h = m.getRequestHeaders();
    int size = (h == null) ? 0 : h.length;

    for (int i = 0; i < size; i++) {
        copy.setRequestHeader(new Header(h[i].getName(), h[i].getValue()));
    }
    copy.setStrictMode(m.isStrictMode());
    if (m instanceof HttpMethodBase) {
        copyHttpMethodBase((HttpMethodBase) m, (HttpMethodBase) copy);
    }
    if (m instanceof EntityEnclosingMethod) {
        copyEntityEnclosingMethod((EntityEnclosingMethod) m, (EntityEnclosingMethod) copy);
    }
    return copy;
}

From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java

/**
 * ?log./* ww  w  .  j  a va 2s .c om*/
 * 
 * @param httpMethod
 *            the http method
 * @return the http method attribute map for log
 */
private static Map<String, Object> getHttpMethodRequestAttributeMapForLog(HttpMethod httpMethod) {
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    try {
        map.put("httpMethod.getName()", httpMethod.getName());
        map.put("httpMethod.getURI()", httpMethod.getURI().toString());
        map.put("httpMethod.getPath()", httpMethod.getPath());
        map.put("httpMethod.getQueryString()", httpMethod.getQueryString());

        map.put("httpMethod.getRequestHeaders()", httpMethod.getRequestHeaders());

        map.put("httpMethod.getDoAuthentication()", httpMethod.getDoAuthentication());
        map.put("httpMethod.getFollowRedirects()", httpMethod.getFollowRedirects());
        map.put("httpMethod.getHostAuthState()", httpMethod.getHostAuthState().toString());

        // HttpMethodParams httpMethodParams = httpMethod.getParams();
        // map.put("httpMethod.getParams()", httpMethodParams);
        map.put("httpMethod.getProxyAuthState()", httpMethod.getProxyAuthState().toString());

    } catch (Exception e) {
        log.error(e.getClass().getName(), e);
    }
    return map;
}

From source file:fr.cls.atoll.motu.library.cas.HttpClientCAS.java

public static String debugHttpMethod(HttpMethod method) {
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("\nName:");
    stringBuffer.append(method.getName());
    stringBuffer.append("\n");
    stringBuffer.append("\nPath:");
    stringBuffer.append(method.getPath());
    stringBuffer.append("\n");
    stringBuffer.append("\nQueryString:");
    stringBuffer.append(method.getQueryString());
    stringBuffer.append("\n");
    stringBuffer.append("\nUri:");
    try {//from  ww  w. j  a  v a2  s.  c  om
        stringBuffer.append(method.getURI().toString());
    } catch (URIException e) {
        // Do nothing
    }
    stringBuffer.append("\n");
    HttpMethodParams httpMethodParams = method.getParams();
    stringBuffer.append("\nHttpMethodParams:");
    stringBuffer.append(httpMethodParams.toString());

    return stringBuffer.toString();

}

From source file:com.netflix.postreview.ExtendedCrucibleSession.java

@Override
protected void adjustHttpHeader(HttpMethod method) {
    //method.addRequestHeader(new Header("Authorization", "Basic " + StringUtil.encode(getUsername() + ":" + getPassword())));
    if (getAuthToken() != null) {
        String qs = method.getQueryString();
        if (qs == null)
            qs = "";
        if (qs.length() > 0)
            qs = qs + "&";
        method.setQueryString(qs + "FEAUTH=" + getAuthToken());
    }//from  w  w  w.  ja  va 2 s  .co  m
}

From source file:edu.utah.further.core.ws.HttpResponseTo.java

/**
 * Copy-constructor from an {@link HttpMethod}.
 * /* w w w.j a  v  a 2 s  . c  om*/
 * @param method
 *            method to copy fields from
 */
public HttpResponseTo(final HttpMethod method) throws IOException {
    this.httpMethod = edu.utah.further.core.api.ws.HttpMethod.valueOf(method.getName());
    this.statusLine = method.getStatusLine();

    for (final Header header : method.getResponseHeaders()) {
        this.responseHeaders.addHeader(new Header(header.getName(), header.getValue()));
    }

    this.path = method.getPath();
    this.queryString = method.getQueryString();
    this.responseBody = method.getResponseBody();
    setParams(method.getParams());
}

From source file:net.sourceforge.jwbf.actions.HttpActionClient.java

/**
 * Process a GET Message.//  www. j a v a  2  s .  co m
 * 
 * @param authgets
 *            a
 * @param cp
 *            a
 * @return a returning message, not null
 * @throws IOException on problems
 * @throws CookieException on problems
 * @throws ProcessException on problems
 */
public byte[] get(HttpMethod authgets) throws IOException, CookieException, ProcessException {
    showCookies(client);
    byte[] out = null;
    authgets.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET);
    //      System.err.println(authgets.getParams().getParameter("http.protocol.content-charset"));

    client.executeMethod(authgets);
    LOG.debug(authgets.getURI());
    LOG.debug("GET: " + authgets.getStatusLine().toString());

    out = authgets.getResponseBody();

    // release any connection resources used by the method
    authgets.releaseConnection();
    int statuscode = authgets.getStatusCode();

    if (statuscode == HttpStatus.SC_NOT_FOUND) {
        LOG.warn("Not Found: " + authgets.getQueryString());

        throw new FileNotFoundException(authgets.getQueryString());
    }

    return out;
}

From source file:net.adamcin.httpsig.http.apache3.Http3SignatureAuthScheme.java

public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException {
    if (credentials instanceof SignerCredentials) {
        SignerCredentials creds = (SignerCredentials) credentials;
        String headers = this.getParameter(Constants.HEADERS);
        String algorithms = this.getParameter(Constants.ALGORITHMS);

        Challenge challenge = new Challenge(this.getRealm(), Constants.parseTokens(headers),
                Challenge.parseAlgorithms(algorithms));

        Signer signer = creds.getSigner();
        if (signer != null) {

            if (this.rotate) {
                this.rotate = false;
                if (!signer.rotateKeys(challenge, this.lastAuthz)) {
                    signer.rotateKeys(challenge);
                    return null;
                }/*from w  w  w. j a v a2 s  .  co  m*/
            }

            RequestContent.Builder sigBuilder = new RequestContent.Builder();

            sigBuilder.setRequestTarget(method.getName(),
                    method.getPath() + (method.getQueryString() != null ? "?" + method.getQueryString() : ""));

            for (Header header : method.getRequestHeaders()) {
                sigBuilder.addHeader(header.getName(), header.getValue());
            }

            if (sigBuilder.build().getDate() == null) {
                sigBuilder.addDateNow();
                method.addRequestHeader(Constants.HEADER_DATE, sigBuilder.build().getDate());
            }

            Authorization authorization = creds.getSigner().sign(sigBuilder.build());
            this.lastAuthz = authorization;
            if (authorization != null) {
                return authorization.getHeaderValue();
            }
        }
    }

    return null;
}

From source file:net.sourceforge.jwbf.actions.HttpActionClient.java

/**
 * Process a GET Message.//from   w w  w .  ja  v  a 2  s  .  c  o  m
 * 
 * @param authgets
 *            a
 * @param cp
 *            a
 * @return a returning message, not null
 * @throws IOException on problems
 * @throws CookieException on problems
 * @throws ProcessException on problems
 */
protected String get(HttpMethod authgets, ContentProcessable cp)
        throws IOException, CookieException, ProcessException {
    showCookies(client);
    String out = "";
    authgets.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET);
    //      System.err.println(authgets.getParams().getParameter("http.protocol.content-charset"));

    client.executeMethod(authgets);
    cp.validateReturningCookies(client.getState().getCookies(), authgets);
    LOG.debug(authgets.getURI());
    LOG.debug("GET: " + authgets.getStatusLine().toString());

    out = authgets.getResponseBodyAsString();

    out = cp.processReturningText(out, authgets);
    // release any connection resources used by the method
    authgets.releaseConnection();
    int statuscode = authgets.getStatusCode();

    if (statuscode == HttpStatus.SC_NOT_FOUND) {
        LOG.warn("Not Found: " + authgets.getQueryString());

        throw new FileNotFoundException(authgets.getQueryString());
    }

    return out;
}