Example usage for org.apache.commons.httpclient.params HttpMethodParams USER_AGENT

List of usage examples for org.apache.commons.httpclient.params HttpMethodParams USER_AGENT

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpMethodParams USER_AGENT.

Prototype

String USER_AGENT

To view the source code for org.apache.commons.httpclient.params HttpMethodParams USER_AGENT.

Click Source Link

Usage

From source file:com.panoramagl.downloaders.PLHTTPFileDownloader.java

/**download methods*/

@Override//from   w ww .ja v  a  2  s .c  o  m
protected byte[] downloadFile() {
    this.setRunning(true);
    byte[] result = null;
    InputStream is = null;
    ByteArrayOutputStream bas = null;
    String url = this.getURL();
    PLFileDownloaderListener listener = this.getListener();
    boolean hasListener = (listener != null);
    int responseCode = -1;
    long startTime = System.currentTimeMillis();
    // HttpClient instance
    HttpClient client = new HttpClient();
    // Method instance
    HttpMethod method = new GetMethod(url);
    // Method parameters
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.USER_AGENT, "PanoramaGL Android");
    methodParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(this.getMaxAttempts(), false));
    try {
        // Execute the method
        responseCode = client.executeMethod(method);
        if (responseCode != HttpStatus.SC_OK)
            throw new IOException(method.getStatusText());
        // Get content length
        Header header = method.getRequestHeader("Content-Length");
        long contentLength = (header != null ? Long.parseLong(header.getValue()) : 1);
        if (this.isRunning()) {
            if (hasListener)
                listener.didBeginDownload(url, startTime);
        } else
            throw new PLRequestInvalidatedException(url);
        // Get response body as stream
        is = method.getResponseBodyAsStream();
        bas = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        int length = 0, total = 0;
        // Read stream
        while ((length = is.read(buffer)) != -1) {
            if (this.isRunning()) {
                bas.write(buffer, 0, length);
                total += length;
                if (hasListener)
                    listener.didProgressDownload(url, (int) (((float) total / (float) contentLength) * 100.0f));
            } else
                throw new PLRequestInvalidatedException(url);
        }
        if (total == 0)
            throw new IOException("Request data has invalid size (0)");
        // Get data
        if (this.isRunning()) {
            result = bas.toByteArray();
            if (hasListener)
                listener.didEndDownload(url, result, System.currentTimeMillis() - startTime);
        } else
            throw new PLRequestInvalidatedException(url);
    } catch (Throwable e) {
        if (this.isRunning()) {
            PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            if (hasListener)
                listener.didErrorDownload(url, e.toString(), responseCode, result);
        }
    } finally {
        if (bas != null) {
            try {
                bas.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        // Release the connection
        method.releaseConnection();
    }
    this.setRunning(false);
    return result;
}

From source file:com.owncloud.android.oc_framework.network.webdav.WebdavClient.java

/**
 * Constructor//from w w w  . j a  v a2s  .  c o m
 */
public WebdavClient(HttpConnectionManager connectionMgr) {
    super(connectionMgr);
    Log.d(TAG, "Creating WebdavClient");
    getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
    getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    mFollowRedirects = true;
    mSsoSessionCookie = null;
}

From source file:eu.alefzero.webdav.WebdavClient.java

/**
 * Constructor/*from ww w.j  av  a2 s  . c  o  m*/
 */
public WebdavClient(HttpConnectionManager connectionMgr) {
    super(connectionMgr);
    Log_OC.d(TAG, "Creating WebdavClient");
    getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
    getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    mFollowRedirects = true;
    mSsoSessionCookie = null;
    mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
}

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

/**
 * Gets the http method./*  w w  w  . j  ava 2s.  co  m*/
 * 
 * @param httpClientConfig
 *            the http client config
 * @return the http method
 * @throws HttpClientException
 *             the http client util exception
 */
private static HttpMethod getHttpMethod(HttpClientConfig httpClientConfig) throws HttpClientException {
    if (log.isDebugEnabled()) {
        log.debug("[httpClientConfig]:{}", JsonUtil.format(httpClientConfig));
    }

    HttpMethod httpMethod = setUriAndParams(httpClientConfig);
    HttpMethodParams httpMethodParams = httpMethod.getParams();
    // TODO
    httpMethodParams.setParameter(HttpMethodParams.USER_AGENT, DEFAULT_USER_AGENT);

    // ????
    httpMethodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    return httpMethod;
}

From source file:com.cerema.cloud2.lib.resources.status.GetRemoteStatusOperation.java

private boolean tryConnection(OwnCloudClient client) {
    boolean retval = false;
    GetMethod get = null;//from  w w  w . ja v a 2  s .c  om
    String baseUrlSt = client.getBaseUri().toString();
    try {
        get = new GetMethod(baseUrlSt + AccountUtils.STATUS_PATH);

        HttpParams params = get.getParams().getDefaultParams();
        params.setParameter(HttpMethodParams.USER_AGENT, OwnCloudClientManagerFactory.getUserAgent());
        get.getParams().setDefaults(params);

        client.setFollowRedirects(false);
        boolean isRedirectToNonSecureConnection = false;
        int status = client.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT);
        mLatestResult = new RemoteOperationResult((status == HttpStatus.SC_OK), status,
                get.getResponseHeaders());

        String redirectedLocation = mLatestResult.getRedirectedLocation();
        while (redirectedLocation != null && redirectedLocation.length() > 0 && !mLatestResult.isSuccess()) {

            isRedirectToNonSecureConnection |= (baseUrlSt.startsWith("https://")
                    && redirectedLocation.startsWith("http://"));
            get.releaseConnection();
            get = new GetMethod(redirectedLocation);
            status = client.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT);
            mLatestResult = new RemoteOperationResult((status == HttpStatus.SC_OK), status,
                    get.getResponseHeaders());
            redirectedLocation = mLatestResult.getRedirectedLocation();
        }

        String response = get.getResponseBodyAsString();
        if (status == HttpStatus.SC_OK) {
            JSONObject json = new JSONObject(response);
            if (!json.getBoolean(NODE_INSTALLED)) {
                mLatestResult = new RemoteOperationResult(
                        RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
            } else {
                String version = json.getString(NODE_VERSION);
                OwnCloudVersion ocVersion = new OwnCloudVersion(version);
                if (!ocVersion.isVersionValid()) {
                    mLatestResult = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION);

                } else {
                    // success
                    if (isRedirectToNonSecureConnection) {
                        mLatestResult = new RemoteOperationResult(
                                RemoteOperationResult.ResultCode.OK_REDIRECT_TO_NON_SECURE_CONNECTION);
                    } else {
                        mLatestResult = new RemoteOperationResult(
                                baseUrlSt.startsWith("https://") ? RemoteOperationResult.ResultCode.OK_SSL
                                        : RemoteOperationResult.ResultCode.OK_NO_SSL);
                    }

                    ArrayList<Object> data = new ArrayList<Object>();
                    data.add(ocVersion);
                    mLatestResult.setData(data);
                    retval = true;
                }
            }

        } else {
            mLatestResult = new RemoteOperationResult(false, status, get.getResponseHeaders());
        }

    } catch (JSONException e) {
        mLatestResult = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);

    } catch (Exception e) {
        mLatestResult = new RemoteOperationResult(e);

    } finally {
        if (get != null)
            get.releaseConnection();
    }

    if (mLatestResult.isSuccess()) {
        Log_OC.i(TAG, "Connection check at " + baseUrlSt + ": " + mLatestResult.getLogMessage());

    } else if (mLatestResult.getException() != null) {
        Log_OC.e(TAG, "Connection check at " + baseUrlSt + ": " + mLatestResult.getLogMessage(),
                mLatestResult.getException());

    } else {
        Log_OC.e(TAG, "Connection check at " + baseUrlSt + ": " + mLatestResult.getLogMessage());
    }

    return retval;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Create basic http client with default params.
 *
 * @return HttpClient instance/*from  ww  w .  j  a  v a2  s  .c  o  m*/
 */
private static HttpClient getBaseInstance() {
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, IE_USER_AGENT);
    httpClient.getParams().setParameter(HttpClientParams.MAX_REDIRECTS, MAX_REDIRECTS);
    httpClient.getParams().setCookiePolicy("DavMailCookieSpec");
    return httpClient;
}

From source file:com.eucalyptus.webui.server.DownloadsWebBackend.java

public static ArrayList<DownloadInfo> getDownloads(String downloadsUrl) {
    ArrayList<DownloadInfo> downloadsList = Lists.newArrayList();

    HttpClient httpClient = new HttpClient();

    //set User-Agent
    String clientVersion = (String) httpClient.getParams().getDefaults()
            .getParameter(HttpMethodParams.USER_AGENT);
    String javaVersion = System.getProperty("java.version");
    String osName = System.getProperty("os.name");
    String osArch = System.getProperty("os.arch");
    String eucaVersion = System.getProperty("euca.version");
    String extraVersion = System.getProperty("euca.extra_version");

    // Jakarta Commons-HttpClient/3.1 (java 1.6.0_24; Linux amd64) Eucalyptus/3.1.0-1.el6
    String userAgent = clientVersion + " (java " + javaVersion + "; " + osName + " " + osArch + ") Eucalyptus/"
            + eucaVersion;/*from ww  w  . ja  v a 2  s  . c  o  m*/
    if (extraVersion != null) {
        userAgent = userAgent + "-" + extraVersion;
    }

    httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);

    //support for http proxy
    if (HttpServerBootstrapper.httpProxyHost != null && (HttpServerBootstrapper.httpProxyHost.length() > 0)) {
        String proxyHost = HttpServerBootstrapper.httpProxyHost;
        if (HttpServerBootstrapper.httpProxyPort != null
                && (HttpServerBootstrapper.httpProxyPort.length() > 0)) {
            int proxyPort = Integer.parseInt(HttpServerBootstrapper.httpProxyPort);
            httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
        } else {
            httpClient.getHostConfiguration().setProxyHost(new ProxyHost(proxyHost));
        }
    }
    GetMethod method = new GetMethod(downloadsUrl);
    method.getParams().setSoTimeout(TIMEOUT);

    try {
        httpClient.executeMethod(method);
        String str = "";
        InputStream in = method.getResponseBodyAsStream();
        byte[] readBytes = new byte[1024];
        int bytesRead = -1;
        while ((bytesRead = in.read(readBytes)) > 0) {
            str += new String(readBytes, 0, bytesRead);
        }
        String entries[] = str.split("[\\r\\n]+");
        for (int i = 0; i < entries.length; i++) {
            String entry[] = entries[i].split("\\t");
            if (entry.length == 3) {
                downloadsList.add(new DownloadInfo(entry[0], entry[1], entry[2]));
            }
        }
    } catch (MalformedURLException e) {
        LOG.error("Malformed URL exception: " + downloadsUrl, e);
        LOG.debug(e, e);
    } catch (IOException e) {
        LOG.error("I/O exception", e);
        LOG.debug(e, e);
    } finally {
        method.releaseConnection();
    }
    return downloadsList;
}

From source file:com.gisgraphy.rest.RestClient.java

/**
        //w  w w  .ja  v  a 2s  .  c  om
        
/**
 * @param multiThreadedHttpConnectionManager
 *                The
 * @link {@link MultiThreadedHttpConnectionManager} that the fulltext search
 *       engine will use
 * @throws RestClientException
 *                 If an error occured
 */
public RestClient(MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager)
        throws RestClientException {
    if (multiThreadedHttpConnectionManager == null) {
        throw new RestClientException("multiThreadedHttpConnectionManager can not be null");
    }
    this.httpClient = new HttpClient(multiThreadedHttpConnectionManager);
    HttpClientParams httpClientParams = new HttpClientParams();
    httpClientParams.setHttpElementCharset("utf8");
    httpClientParams.setConnectionManagerTimeout(15000);
    httpClientParams.setParameter(HttpMethodParams.USER_AGENT, ClientConfig.CLIENT_USER_AGENT);
    httpClient.setParams(httpClientParams);

    if (this.httpClient == null) {
        throw new RestClientException(
                "Can not instanciate http client with multiThreadedHttpConnectionManager : "
                        + multiThreadedHttpConnectionManager);
    }
}

From source file:ir.keloud.android.lib.common.KeloudClient.java

/**
 * Constructor/*from w w w  .  j a  v a2 s . com*/
 */
public KeloudClient(Uri baseUri, HttpConnectionManager connectionMgr) {
    super(connectionMgr);

    if (baseUri == null) {
        throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL");
    }
    mBaseUri = baseUri;

    mInstanceNumber = sIntanceCounter++;
    Log_OC.d(TAG + " #" + mInstanceNumber, "Creating KeloudClient");

    String userAgent = KeloudClientManagerFactory.getUserAgent();
    getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
    getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    getParams().setParameter(PARAM_SINGLE_COOKIE_HEADER, // to avoid problems with some web servers
            PARAM_SINGLE_COOKIE_HEADER_VALUE);

    applyProxySettings();

    clearCredentials();
}

From source file:com.owncloud.android.lib.common.OwnCloudClient.java

/**
 * Constructor//from   w w w.  j a va2 s  .  co  m
 */
public OwnCloudClient(Uri baseUri, HttpConnectionManager connectionMgr) {
    super(connectionMgr);

    if (baseUri == null) {
        throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL");
    }
    mBaseUri = baseUri;

    mInstanceNumber = sIntanceCounter++;
    Log_OC.d(TAG + " #" + mInstanceNumber, "Creating OwnCloudClient");

    getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
    getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    getParams().setParameter(PARAM_SINGLE_COOKIE_HEADER, // to avoid problems with some web servers
            PARAM_SINGLE_COOKIE_HEADER_VALUE);

    applyProxySettings();

    clearCredentials();
}