Example usage for org.apache.http.params HttpProtocolParams setUserAgent

List of usage examples for org.apache.http.params HttpProtocolParams setUserAgent

Introduction

In this page you can find the example usage for org.apache.http.params HttpProtocolParams setUserAgent.

Prototype

public static void setUserAgent(HttpParams httpParams, String str) 

Source Link

Usage

From source file:com.neudesic.azureservicebustest.asynchttp.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*w  ww  .  j  ava  2s .  co m*/
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }

            request.addHeader("Accept", "*/*"); // SVG 5/8/2013 - intercept this to add for our API
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:org.vietspider.net.client.impl.AnonymousHttpClient.java

@Override
protected HttpParams createHttpParams() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    // determine the release version from packaged version info
    final VersionInfo vi = VersionInfo.loadVersionInfo("org.apache.http.client", getClass().getClassLoader());
    final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
    HttpProtocolParams.setUserAgent(params, "Apache-HttpClient/" + release + " (java 1.4)");

    return params;
}

From source file:com.lgallardo.qbittorrentclient.JSONParser.java

public JSONObject getJSONFromUrl(String url) throws JSONParserStatusCodeException {

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }// www.  j ava2 s. c  o m

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient(httpParameters);
    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        // set http parameters

        url = protocol + "://" + hostname + ":" + port + "/" + url;

        //            Log.d("Debug", "url:" + url);

        HttpGet httpget = new HttpGet(url);

        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

        // Build JSON
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();

        // try parse the string to a JSON object
        jObj = new JSONObject(json);

    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    } catch (UnsupportedEncodingException e) {
        Log.e("JSON", "UnsupportedEncodingException: " + e.toString());

    } catch (ClientProtocolException e) {
        Log.e("JSON", "ClientProtocolException: " + e.toString());
        e.printStackTrace();
    } catch (SSLPeerUnverifiedException e) {
        Log.e("JSON", "SSLPeerUnverifiedException: " + e.toString());
        throw new JSONParserStatusCodeException(NO_PEER_CERTIFICATE);
    } catch (IOException e) {
        Log.e("JSON", "IOException: " + e.toString());
        // e.printStackTrace();
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("JSON", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    // return JSON String
    return jObj;
}

From source file:cn.ctyun.amazonaws.regions.RegionUtils.java

/**
 * Fetches a file from the URL given and returns an input stream to it.
 *//*from w  w  w . j a v  a 2  s.  c o m*/
private static InputStream fetchFile(String url)
        throws IOException, ClientProtocolException, FileNotFoundException {

    HttpParams httpClientParams = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(httpClientParams, VersionInfoUtils.getUserAgent());
    HttpClient httpclient = new DefaultHttpClient(httpClientParams);
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        return entity.getContent();
    }
    return null;
}

From source file:com.box.androidlib.BoxFileDownload.java

/**
 * Execute a file download./*from w ww . j  a  v a  2  s . co m*/
 * 
 * @param fileId
 *            The file_id of the file to be downloaded
 * @param destinationOutputStreams
 *            OutputStreams to which the data should be written to as it is downloaded.
 * @param versionId
 *            The version_id of the version of the file to download. Set to null to download the latest version of the file.
 * @return a response handler
 * @throws IOException
 *             Can be thrown if there was a connection error, or if destination file could not be written.
 */
public DefaultResponseParser execute(final long fileId, final OutputStream[] destinationOutputStreams,
        final Long versionId) throws IOException {

    final DefaultResponseParser handler = new DefaultResponseParser();

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(BoxConfig.getInstance().getDownloadUrlScheme());
    builder.encodedAuthority(BoxConfig.getInstance().getDownloadUrlAuthority());
    builder.path(BoxConfig.getInstance().getDownloadUrlPath());
    builder.appendPath(mAuthToken);
    builder.appendPath(String.valueOf(fileId));
    if (versionId != null) {
        builder.appendPath(String.valueOf(versionId));
    }

    List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters();
    if (customQueryParams != null && customQueryParams.size() > 0) {
        for (BasicNameValuePair param : customQueryParams) {
            builder.appendQueryParameter(param.getName(), param.getValue());
        }
    }

    // We normally prefer to use HttpUrlConnection, however that appears to fail for certain types of files. For downloads, it appears DefaultHttpClient
    // works more reliably.
    final DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(httpclient.getParams(), BoxConfig.getInstance().getUserAgent());
    HttpGet httpGet;

    String theUri = builder.build().toString();
    if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        //DevUtils.logcat("User-Agent : " + HttpProtocolParams.getUserAgent(httpclient.getParams()));
        DevUtils.logcat("Box Request: " + theUri);
    }
    try {
        httpGet = new HttpGet(new URI(theUri));
    } catch (URISyntaxException e) {
        throw new IOException("Invalid Download URL");
    }
    httpGet.setHeader("Connection", "close");
    httpGet.setHeader("Accept-Language", BoxConfig.getInstance().getAcceptLanguage());
    HttpResponse httpResponse = httpclient.execute(httpGet);

    int responseCode = httpResponse.getStatusLine().getStatusCode();

    if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        DevUtils.logcat("Box Response: " + responseCode);
        //            Header[] headers = httpResponse.getAllHeaders();
        //            for (Header header : headers) {
        //                DevUtils.logcat("Response Header: " + header.toString());
        //            }
    }

    // Server returned a 503 Service Unavailable. Usually means a temporary unavailability.
    if (responseCode == HttpStatus.SC_SERVICE_UNAVAILABLE) {
        //            if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        //                DevUtils.logcat("HTTP Response Code: " + HttpStatus.SC_SERVICE_UNAVAILABLE);
        //            }
        handler.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE);
        return handler;
    }

    InputStream is = httpResponse.getEntity().getContent();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        // Grab the first 100 bytes and check for an error string.
        // Not a good way for the server to respond with errors but that's the way it is for now.
        final byte[] errorCheckBuffer = new byte[FILE_ERROR_SIZE];
        // Three cases here: error, no error && file size == 0, no error && file size > 0.
        // The first case will be handled by parsing the error check buffer. The second case will result in mBytesTransferred == 0,
        // no real bytes will be transferred but we still treat as success case. The third case is normal success case.
        mBytesTransferred = Math.max(0, is.read(errorCheckBuffer));
        final String str = new String(errorCheckBuffer).trim();
        if (str.equals(FileDownloadListener.STATUS_DOWNLOAD_WRONG_AUTH_TOKEN)) {
            handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_WRONG_AUTH_TOKEN);
        } else if (str.equals(FileDownloadListener.STATUS_DOWNLOAD_RESTRICTED)) {
            handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_RESTRICTED);
        }
        // No error detected
        else {
            // Copy the file to destination if > 0 bytes of file transferred.
            if (mBytesTransferred > 0) {
                for (int i = 0; i < destinationOutputStreams.length; i++) {
                    destinationOutputStreams[i].write(errorCheckBuffer, 0, (int) mBytesTransferred); // Make sure we don't lose that first 100 bytes.
                }

                // Read the rest of the stream and write to the destination OutputStream.
                final byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
                int bufferLength = 0;
                long lastOnProgressPost = 0;
                while (!Thread.currentThread().isInterrupted() && (bufferLength = is.read(buffer)) > 0) {
                    for (int i = 0; i < destinationOutputStreams.length; i++) {
                        destinationOutputStreams[i].write(buffer, 0, bufferLength);
                    }
                    mBytesTransferred += bufferLength;
                    long currTime = SystemClock.uptimeMillis();
                    if (mListener != null && mHandler != null
                            && currTime - lastOnProgressPost > ON_PROGRESS_UPDATE_THRESHOLD) {
                        lastOnProgressPost = currTime;
                        mHandler.post(mOnProgressRunnable);
                    }
                }
                mHandler.post(mOnProgressRunnable);
            }
            for (int i = 0; i < destinationOutputStreams.length; i++) {
                destinationOutputStreams[i].close();
            }
            handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_OK);

            // If download thread was interrupted, set to
            // STATUS_DOWNLOAD_CANCELED
            if (Thread.currentThread().isInterrupted()) {
                httpGet.abort();
                handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_CANCELLED);
            }
        }
    } else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_PERMISSIONS_ERROR);
    } else {
        handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_FAIL);
    }
    httpResponse.getEntity().consumeContent();
    if (httpclient != null && httpclient.getConnectionManager() != null) {
        httpclient.getConnectionManager().closeIdleConnections(500, TimeUnit.MILLISECONDS);
    }
    is.close();

    return handler;
}

From source file:com.doculibre.constellio.utils.ConnectorManagerRequestUtils.java

public static Element sendPost(ConnectorManager connectorManager, String servletPath, Document document) {
    try {/*from w  w w.j a v a  2s.co m*/
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
        HttpProtocolParams.setUseExpectContinue(params, true);

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        // Required protocol interceptors
        httpproc.addInterceptor(new RequestContent());
        httpproc.addInterceptor(new RequestTargetHost());
        // Recommended protocol interceptors
        httpproc.addInterceptor(new RequestConnControl());
        httpproc.addInterceptor(new RequestUserAgent());
        httpproc.addInterceptor(new RequestExpectContinue());

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

        HttpContext context = new BasicHttpContext(null);

        URL connectorManagerURL = new URL(connectorManager.getUrl());
        HttpHost host = new HttpHost(connectorManagerURL.getHost(), connectorManagerURL.getPort());

        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        try {
            HttpEntity requestBody;
            if (document != null) {
                //                 OutputFormat format = OutputFormat.createPrettyPrint();
                OutputFormat format = OutputFormat.createCompactFormat();
                StringWriter stringWriter = new StringWriter();
                XMLWriter xmlWriter = new XMLWriter(stringWriter, format);
                xmlWriter.write(document);
                String xmlAsString = stringWriter.toString();
                requestBody = new StringEntity(xmlAsString, "UTF-8");
            } else {
                requestBody = null;
            }
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }

            String target = connectorManager.getUrl() + servletPath;

            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", target);
            request.setEntity(requestBody);
            LOGGER.info(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            LOGGER.info("<< Response: " + response.getStatusLine());
            String entityText = EntityUtils.toString(response.getEntity());
            LOGGER.info(entityText);
            LOGGER.info("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                LOGGER.info("Connection kept alive...");
            }

            Document xml = DocumentHelper.parseText(entityText);
            return xml.getRootElement();
        } finally {
            conn.close();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.baidu.qa.service.test.client.SoapReqImpl.java

private static String sendSoap(String hosturl, String ip, int port, String action, String method, String xml,
        boolean isHttps) throws Exception {
    if (isHttps) {
        return sendSoapViaHttps(hosturl, ip, port, action, method, xml);
    }//www .  j  a v  a 2s .c om

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");// must be UTF-8
    HttpProtocolParams.setUserAgent(params, "itest-by-HttpCore/4.2");

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    // log.info("ip:port - " + ip + ":" + port );
    HttpHost host = new HttpHost(ip, port);// TODO

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    conn.setSocketTimeout(10000);
    HttpConnectionParams.setSoTimeout(params, 10000);
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    String res = null;

    try {
        // HttpEntity requestBody = new
        // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO
        byte[] b = xml.getBytes("UTF-8"); // must be UTF-8
        InputStream is = new ByteArrayInputStream(b, 0, b.length);

        HttpEntity requestBody = new InputStreamEntity(is, b.length,
                ContentType.create("text/xml;charset=UTF-8"));// must be
        // UTF-8

        // .create("application/xop+xml; charset=UTF-8; type=\"text/xml\""));//
        // TODO

        // RequestEntity re = new InputStreamRequestEntity(is, b.length,
        // "application/xop+xml; charset=UTF-8; type=\"text/xml\"");
        // postmethod.setRequestEntity(re);

        if (!conn.isOpen()) {
            Socket socket = new Socket(host.getHostName(), host.getPort());
            conn.bind(socket, params);
        }
        BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", action);

        // add the 3 headers below
        request.addHeader("Accept-Encoding", "gzip,deflate");
        request.addHeader("SOAPAction", hosturl + action + method);// SOAP action
        request.addHeader("uuid", "itest");// for editor token of DR-Api

        request.setEntity(requestBody);
        log.info(">> Request URI: " + request.getRequestLine().getUri());

        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);

        log.info("<< Response: " + response.getStatusLine());

        String contentEncoding = null;
        Header ce = response.getEntity().getContentEncoding();
        if (ce != null) {
            contentEncoding = ce.getValue();
        }

        if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
            GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent());
            Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8"));
            StringBuilder sb = new StringBuilder();
            while (in.hasNextLine()) {
                sb.append(in.nextLine()).append(System.getProperty("line.separator"));
            }
            res = sb.toString();
        } else {
            res = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        log.info(res);

        log.info("==============");
        if (!connStrategy.keepAlive(response, context)) {
            conn.close();
        } else {
            log.info("Connection kept alive...");
        }
    } finally {
        try {
            conn.close();
        } catch (IOException e) {
        }
    }
    return res;
}

From source file:at.general.solutions.android.ical.remote.HttpDownloadThread.java

@Override
public void run() {
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, USER_AGENT);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient client = new DefaultHttpClient(cm, params);

    if (useAuthentication) {
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(remoteUsername, remotePassword));
    }//from   w  ww .j  a va  2 s. c o m

    HttpGet get = new HttpGet(remoteUrl);

    try {
        super.sendInitMessage(R.string.downloading);

        HttpResponse response = client.execute(get);
        Log.d(LOG_TAG, response.getStatusLine().getReasonPhrase() + " "
                + isGoodResponse(response.getStatusLine().getStatusCode()));
        if (isGoodResponse(response.getStatusLine().getStatusCode())) {
            HttpEntity entity = response.getEntity();

            InputStream instream = entity.getContent();
            if (instream == null) {
                super.sendErrorMessage(R.string.couldnotConnectToRemoteserver);
                return;
            }
            if (entity.getContentLength() > Integer.MAX_VALUE) {
                super.sendErrorMessage(R.string.remoteFileTooLarge);
                return;
            }
            int i = (int) entity.getContentLength();
            if (i < 0) {
                i = 4096;
            }
            String charset = EntityUtils.getContentCharSet(entity);
            if (charset == null) {
                charset = encoding;
            }
            if (charset == null) {
                charset = HTTP.DEFAULT_CONTENT_CHARSET;
            }
            Reader reader = new InputStreamReader(instream, charset);
            CharArrayBuffer buffer = new CharArrayBuffer(i);

            super.sendMaximumMessage(i);

            try {
                char[] tmp = new char[1024];
                int l;
                while ((l = reader.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                    super.sendProgressMessage(buffer.length());
                }
            } finally {
                reader.close();
            }

            super.sendFinishedMessage(buffer.toString());
        } else {
            int errorMsg = R.string.couldnotConnectToRemoteserver;
            if (isAccessDenied(response.getStatusLine().getStatusCode())) {
                errorMsg = R.string.accessDenied;
            } else if (isFileNotFound(response.getStatusLine().getStatusCode())) {
                errorMsg = R.string.remoteFileNotFound;
            }
            super.sendErrorMessage(errorMsg);
        }
    } catch (UnknownHostException e) {
        super.sendErrorMessage(R.string.unknownHostException, e);
        Log.e(LOG_TAG, "Error occured", e);
    } catch (Throwable e) {
        super.sendErrorMessage(R.string.couldnotConnectToRemoteserver, e);
        Log.e(LOG_TAG, "Error occured", e);
    }

    finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.eclipse.aether.transport.http.HttpTransporter.java

private static void configureClient(HttpParams params, RepositorySystemSession session,
        RemoteRepository repository, HttpHost proxy) {
    AuthParams.setCredentialCharset(params,
            ConfigUtils.getString(session, ConfigurationProperties.DEFAULT_HTTP_CREDENTIAL_ENCODING,
                    ConfigurationProperties.HTTP_CREDENTIAL_ENCODING + "." + repository.getId(),
                    ConfigurationProperties.HTTP_CREDENTIAL_ENCODING));
    ConnRouteParams.setDefaultProxy(params, proxy);
    HttpConnectionParams.setConnectionTimeout(params,
            ConfigUtils.getInteger(session, ConfigurationProperties.DEFAULT_CONNECT_TIMEOUT,
                    ConfigurationProperties.CONNECT_TIMEOUT + "." + repository.getId(),
                    ConfigurationProperties.CONNECT_TIMEOUT));
    HttpConnectionParams.setSoTimeout(params,
            ConfigUtils.getInteger(session, ConfigurationProperties.DEFAULT_REQUEST_TIMEOUT,
                    ConfigurationProperties.REQUEST_TIMEOUT + "." + repository.getId(),
                    ConfigurationProperties.REQUEST_TIMEOUT));
    HttpProtocolParams.setUserAgent(params, ConfigUtils.getString(session,
            ConfigurationProperties.DEFAULT_USER_AGENT, ConfigurationProperties.USER_AGENT));
}

From source file:ca.mudar.mtlaucasou.services.SyncService.java

/**
 * Generate and return a {@link HttpClient} configured for general use,
 * including setting an application-specific user-agent string.
 *//*ww  w. j a  va 2 s  . co  m*/
public static HttpClient getHttpClient(Context context) {
    final HttpParams params = new BasicHttpParams();

    // Use generous timeouts for slow mobile networks
    HttpConnectionParams.setConnectionTimeout(params, 20 * SECOND_IN_MILLIS);
    HttpConnectionParams.setSoTimeout(params, 20 * SECOND_IN_MILLIS);

    HttpConnectionParams.setSocketBufferSize(params, 8192);
    HttpProtocolParams.setUserAgent(params, buildUserAgent(context));

    final DefaultHttpClient client = new DefaultHttpClient(params);

    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            // Add header to accept gzip content
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
        }
    });

    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) {
            // Inflate any responses compressed with gzip
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    return client;
}