Example usage for org.apache.http.params BasicHttpParams BasicHttpParams

List of usage examples for org.apache.http.params BasicHttpParams BasicHttpParams

Introduction

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

Prototype

public BasicHttpParams() 

Source Link

Usage

From source file:br.ufg.inf.es.fs.contpatri.mobile.webservice.Autenticar.java

@Override
protected Void doInBackground(final Void... params) {

    /*//from  w ww  .  jav a 2 s  .  c  o m
     * Ajuste de timeout.
     */
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setSoTimeout(httpParams, timeout);

    /*
     * Configuraes iniciais para estabelecer uma conexo HTTP.
     */
    final DefaultHttpClient httpCliente = new DefaultHttpClient(httpParams);
    final HttpPost httpPost = new HttpPost(ListaLinks.URL_AUTENTICAR);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");

    HttpResponse httpResponse;

    try {

        httpPost.setEntity(new StringEntity(usuario.toJson()));
        httpResponse = httpCliente.execute(httpPost);

        /*
         * Se a resposta ao servidor for uma de cdigo maior ou igual a 400,
         * significa que houve erro que no houve comunicao com o
         * WebService. Caso contrrio a comunicao foi bem sucedida.
         */
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            sucesso = false;
            mensagem = httpResponse.getStatusLine().getReasonPhrase();
        } else {

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
            StringBuilder builder = new StringBuilder();

            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }

            final JSONObject json = new JSONObject(builder.toString());

            sucesso = json.getBoolean("sucesso");
            mensagem = json.getString("mensagem");

        }

    } catch (final UnsupportedEncodingException e) {
        Log.e(Autenticar.class.getSimpleName(), "", e);
    } catch (final ClientProtocolException e) {
        Log.e(Autenticar.class.getSimpleName(), "", e);
    } catch (final IOException e) {
        Log.e(Autenticar.class.getSimpleName(), "", e);
    } catch (final JSONException e) {
        Log.e(Autenticar.class.getSimpleName(), "", e);
    }

    sucesso = true;

    return null;
}

From source file:es.uma.lcc.tasks.PictureDetailsTask.java

@Override
public Void doInBackground(Void... args) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    int width, height;
    final HttpParams params = new BasicHttpParams();
    HttpClientParams.setRedirecting(params, false);
    httpclient.setParams(params);//from   w w w. ja va2s . c o  m
    String target = SERVERURL + "?" + QUERYSTRING_ACTION + "=" + ACTION_PICTUREDETAILS + "&"
            + QUERYSTRING_PICTUREID + "=" + mPicId;
    HttpGet httpget = new HttpGet(target);
    while (mCookie == null)
        mCookie = mMainActivity.getCurrentCookie();

    httpget.setHeader("Cookie", mCookie.getName() + "=" + mMainActivity.getCurrentCookie().getValue());
    try {
        HttpResponse response = httpclient.execute(httpget);

        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) {
            throw new IOException("Invalid response from server: " + status.toString());
        }

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = entity.getContent();
            ByteArrayOutputStream content = new ByteArrayOutputStream();

            // Read response into a buffered stream
            int readBytes = 0;
            byte[] sBuffer = new byte[256];
            while ((readBytes = inputStream.read(sBuffer)) != -1) {
                content.write(sBuffer, 0, readBytes);
            }
            String result = new String(content.toByteArray());

            try {
                JSONArray jsonArray = new JSONArray(result);
                if (jsonArray.length() == 0) {
                    // should never happen
                    Log.e(APP_TAG, LOG_ERROR + ": Malformed response from server");
                } else {
                    // Elements in a JSONArray keep their order
                    JSONObject successState = jsonArray.getJSONObject(0);
                    if (successState.get(JSON_RESULT).equals(JSON_RESULT_ERROR)) {
                        if (successState.getBoolean(JSON_ISAUTHERROR) && mIsFirstRun) {
                            mIsAuthError = true;
                        } else {
                            Log.e(APP_TAG,
                                    LOG_ERROR + ": Server found an error: " + successState.get(JSON_REASON));
                        }
                    } else {
                        ArrayList<String> users = new ArrayList<String>();
                        ArrayList<String> coords = new ArrayList<String>();
                        ArrayList<String> ids = new ArrayList<String>();
                        JSONObject obj = jsonArray.getJSONObject(0);
                        width = obj.getInt(JSON_IMGWIDTH);
                        height = obj.getInt(JSON_IMGHEIGHT);
                        for (int i = 1; i < jsonArray.length(); i++) {
                            obj = jsonArray.getJSONObject(i);
                            users.add(obj.getString(JSON_USERNAME));
                            coords.add(formatCoordinates(obj.getInt(JSON_HSTART), obj.getInt(JSON_HEND),
                                    obj.getInt(JSON_VSTART), obj.getInt(JSON_VEND)));
                            ids.add(obj.getString(JSON_PERMISSIONID));
                        }
                        Intent intent = new Intent(mMainActivity, PictureDetailsActivity.class);
                        intent.putStringArrayListExtra("users", users);
                        intent.putStringArrayListExtra("coordinates", coords);
                        intent.putStringArrayListExtra("ids", ids);
                        intent.putExtra("height", height);
                        intent.putExtra("width", width);
                        intent.putExtra("picId", mPicId);
                        intent.putExtra("username", mMainActivity.getUserEmail());
                        mMainActivity.startActivityForResult(intent, ACTIVITY_PICTURE_DETAILS);
                    }
                }
            } catch (JSONException jsonEx) {
                Log.e(APP_TAG, LOG_ERROR + ": Malformed JSON response from server");
            }
        } else { // entity is null
            Log.e(APP_TAG, LOG_ERROR + ": null response from server");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.menumomma.chrome2phone.AppEngineClient.java

private HttpResponse makeRequestNoRetry(String urlPath, List<NameValuePair> params, boolean newToken)
        throws Exception {
    // Get auth token for account
    Account account = new Account(mAccountName, "com.google");
    String authToken = getAuthToken(mContext, account);

    if (newToken) { // invalidate the cached token
        AccountManager accountManager = AccountManager.get(mContext);
        accountManager.invalidateAuthToken(account.type, authToken);
        authToken = getAuthToken(mContext, account);
    }/* w  w w .java 2 s.  co  m*/

    // Get ACSID cookie
    DefaultHttpClient client = new DefaultHttpClient();
    String continueURL = Config.BASE_URL;
    URI uri = new URI(AUTH_URL + "?continue=" + URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken);
    HttpGet method = new HttpGet(uri);
    final HttpParams getParams = new BasicHttpParams();
    HttpClientParams.setRedirecting(getParams, false); // continue is not used
    method.setParams(getParams);

    HttpResponse res = client.execute(method);
    Header[] headers = res.getHeaders("Set-Cookie");
    if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) {
        return res;
    }

    String ascidCookie = null;
    for (Header header : headers) {
        if (header.getValue().indexOf("ACSID=") >= 0) {
            // let's parse it
            String value = header.getValue();
            String[] pairs = value.split(";");
            ascidCookie = pairs[0];
        }
    }

    // Make POST request
    uri = new URI(Config.BASE_URL + urlPath);
    HttpPost post = new HttpPost(uri);
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
    post.setEntity(entity);
    post.setHeader("Cookie", ascidCookie);
    post.setHeader("X-Same-Domain", "1"); // XSRF
    res = client.execute(post);
    return res;
}

From source file:com.lonepulse.robozombie.executor.ConfigurationService.java

/**
 * <p>The <i>out-of-the-box</i> configuration for an instance of {@link HttpClient} which will be used for 
 * executing all endpoint requests. Below is a detailed description of all configured properties.</p> 
 * <br>/*from  w w  w  . j av a2s .  c  o m*/
 * <ul>
 * <li>
 * <p><b>HttpClient</b></p>
 * <br>
 * <p>It registers two {@link Scheme}s:</p>
 * <br>
 * <ol>
 *    <li><b>HTTP</b> on port <b>80</b> using sockets from {@link PlainSocketFactory#getSocketFactory}</li>
 *    <li><b>HTTPS</b> on port <b>443</b> using sockets from {@link SSLSocketFactory#getSocketFactory}</li>
 * </ol>
 * 
 * <p>It uses a {@link ThreadSafeClientConnManager} with the following parameters:</p>
 * <br>
 * <ol>
 *    <li><b>Redirecting:</b> enabled</li>
 *    <li><b>Connection Timeout:</b> 30 seconds</li>
 *    <li><b>Socket Timeout:</b> 30 seconds</li>
 *    <li><b>Socket Buffer Size:</b> 12000 bytes</li>
 *    <li><b>User-Agent:</b> via <code>System.getProperty("http.agent")</code></li>
 * </ol>
 * </li>
 * </ul>
 * @return the instance of {@link HttpClient} which will be used for request execution
 * <br><br>
 * @since 1.3.0
 */
@Override
public Configuration getDefault() {

    return new Configuration() {

        @Override
        public HttpClient httpClient() {

            try {

                HttpParams params = new BasicHttpParams();
                HttpClientParams.setRedirecting(params, true);
                HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
                HttpConnectionParams.setSoTimeout(params, 30 * 1000);
                HttpConnectionParams.setSocketBufferSize(params, 12000);
                HttpProtocolParams.setUserAgent(params, System.getProperty("http.agent"));

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

                ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

                return new DefaultHttpClient(manager, params);
            } catch (Exception e) {

                throw new ConfigurationFailedException(e);
            }
        }
    };
}

From source file:io.undertow.server.handlers.HttpContinueAcceptingHandlerTestCase.java

@Test
public void testHttpContinueRejected() throws IOException {
    accept = false;//from  ww w.ja v a 2 s . com
    String message = "My HTTP Request!";
    HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter("http.protocol.wait-for-continue", Integer.MAX_VALUE);

    TestHttpClient client = new TestHttpClient();
    client.setParams(httpParams);
    try {
        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        post.addHeader("Expect", "100-continue");
        post.setEntity(new StringEntity(message));

        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.EXPECTATION_FAILED, result.getStatusLine().getStatusCode());
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.dongfang.net.HttpUtils.java

public HttpUtils(int connTimeout) {
    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connTimeout);
    HttpConnectionParams.setSoTimeout(params, connTimeout);
    HttpConnectionParams.setConnectionTimeout(params, connTimeout);

    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));
    ConnManagerParams.setMaxTotalConnections(params, 10);

    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 1024 * 8);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

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

    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES));

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override/*from   w w w  . j a v  a  2s .  c o m*/
        public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext)
                throws org.apache.http.HttpException, IOException {
            if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {
                httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext httpContext)
                throws org.apache.http.HttpException, IOException {
            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("gzip")) {
                        response.setEntity(new GZipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });
}

From source file:com.android.unit_tests.TestHttpServer.java

public TestHttpServer() throws IOException {
    super();//from  www. j a va  2s . c om
    this.params = new BasicHttpParams();
    this.params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1");
    this.httpproc = new BasicHttpProcessor();
    this.httpproc.addInterceptor(new ResponseDate());
    this.httpproc.addInterceptor(new ResponseServer());
    this.httpproc.addInterceptor(new ResponseContent());
    this.httpproc.addInterceptor(new ResponseConnControl());
    this.connStrategy = new DefaultConnectionReuseStrategy();
    this.responseFactory = new DefaultHttpResponseFactory();
    this.reqistry = new HttpRequestHandlerRegistry();
    this.serversocket = new ServerSocket(0);
}

From source file:com.nanocrawler.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    this.config = config;

    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());
    params.setBooleanParameter("http.protocol.handle-redirects", false);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    if (config.isIncludeHttpsPages()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }/* www.j  ava 2s. co m*/

    connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);
}

From source file:org.devtcg.five.util.streaming.FailfastHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * @param userAgent to report in your HTTP requests.
 * @return FailfastHttpClient for you to use for all your requests.
 *///  w  w w  .  j  a v a2  s. c om
public static FailfastHttpClient newInstance(String userAgent) {
    HttpParams params = new BasicHttpParams();

    // Turn off stale checking.  Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 10 seconds.  Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, READ_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller.  Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Set the specified user agent and register standard protocols.
    if (userAgent != null)
        HttpProtocolParams.setUserAgent(params, userAgent);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager manager = new HackThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new FailfastHttpClient(manager, params);
}

From source file:org.geomajas.layer.common.proxy.LayerHttpServiceImpl.java

public InputStream getStream(final String baseUrl, final LayerAuthentication authentication,
        final String layerId) throws IOException {
    // Create a HTTP client object, which will initiate the connection:
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT);
    SystemDefaultHttpClient client = new SystemDefaultHttpClient(httpParams);

    String url = addCredentialsToUrl(baseUrl, authentication);

    // -- add basic authentication
    if (null != authentication
            && (LayerAuthenticationMethod.BASIC.equals(authentication.getAuthenticationMethod())
                    || LayerAuthenticationMethod.DIGEST.equals(authentication.getAuthenticationMethod()))) {
        // Set up the credentials:
        Credentials creds = new UsernamePasswordCredentials(authentication.getUser(),
                authentication.getPassword());
        AuthScope scope = new AuthScope(parseDomain(url), parsePort(url), authentication.getRealm());
        client.getCredentialsProvider().setCredentials(scope, creds);
    }/*ww w  .  j  av a 2 s . c om*/

    // -- add interceptors if any --
    addInterceptors(client, baseUrl, layerId);

    // Create the GET method with the correct URL:
    HttpGet get = new HttpGet(url);

    // Execute the GET:
    HttpResponse response = client.execute(get);
    log.debug("Response: {} - {}", response.getStatusLine().getStatusCode(),
            response.getStatusLine().getReasonPhrase());

    return new LayerHttpServiceStream(response, client);
}