Example usage for org.apache.http.client.methods HttpRequestBase getParams

List of usage examples for org.apache.http.client.methods HttpRequestBase getParams

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpRequestBase getParams.

Prototype

@Deprecated
    public HttpParams getParams() 

Source Link

Usage

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java

/**
 * Retrieves the list of classifiers for the user.
 * //from   ww w . j  a v  a  2 s .  co  m
 * @return the classifier list
 * @throws UnsupportedEncodingException 
 * @see Classifier
 */
public Classifiers getClassifiers() throws UnsupportedEncodingException {
    HttpRequestBase request = Request.Get("/v1/classifiers").build();
    HttpHost proxy = new HttpHost("10.100.1.124", 3128);
    ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
    try {
        HttpResponse response = execute(request);
        return ResponseUtil.getObject(response, Classifiers.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.java.sip.communicator.service.httputil.HttpUtils.java

/**
 * Executes the method and return the result. Handle ask for password
 * when hitting password protected site.
 * Keep asking for password till user clicks cancel or enters correct
 * password. When 'remember password' is checked password is saved, if this
 * password and username are not correct clear them, if there are correct
 * they stay saved.//from www  .  j  a  v  a  2 s .co  m
 * @param httpClient the configured http client to use.
 * @param req the request for now it is get or post.
 * @param redirectHandler handles redirection, should we redirect and
 * the actual redirect.
 * @param parameters if we are redirecting we can use already filled
 * username and password in order to avoid asking the user twice.
 *
 * @return the result http entity.
 */
private static HttpEntity executeMethod(DefaultHttpClient httpClient, HttpRequestBase req,
        RedirectHandler redirectHandler, List<NameValuePair> parameters) throws Throwable {
    // do it when response (first execution) or till we are unauthorized
    HttpResponse response = null;
    int redirects = 0;
    while (response == null || response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED
            || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
        // if we were unauthorized, lets clear the method and recreate it
        // for new connection with new credentials.
        if (response != null && (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED
                || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN)) {
            if (logger.isDebugEnabled())
                logger.debug("Will retry http connect and " + "credentials input as latest are not correct!");

            throw new AuthenticationException("Authorization needed");
        } else
            response = httpClient.execute(req);

        // if user click cancel no need to retry, stop trying
        if (!((HTTPCredentialsProvider) httpClient.getCredentialsProvider()).retry()) {
            if (logger.isDebugEnabled())
                logger.debug("User canceled credentials input.");
            break;
        }

        // check for post redirect as post redirects are not handled
        // automatically
        // RFC2616 (10.3 Redirection 3xx).
        // The second request (forwarded method) can only be a GET or HEAD.
        Header locationHeader = response.getFirstHeader("location");

        if (locationHeader != null && req instanceof HttpPost
                && (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                        || response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY
                        || response.getStatusLine().getStatusCode() == HttpStatus.SC_SEE_OTHER)
                && redirects < MAX_REDIRECTS) {
            HttpRequestBase oldreq = req;
            oldreq.abort();

            String newLocation = locationHeader.getValue();

            // lets ask redirection handler if any
            if (redirectHandler != null && redirectHandler.handleRedirect(newLocation, parameters)) {
                return null;
            }

            req = new HttpGet(newLocation);
            req.setParams(oldreq.getParams());
            req.setHeaders(oldreq.getAllHeaders());

            redirects++;
            response = httpClient.execute(req);
        }
    }

    // if we finally managed to login return the result.
    if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return response.getEntity();
    }

    // is user has canceled no result needed.
    return null;
}

From source file:com.opower.rest.client.generator.executors.ApacheHttpClient4Executor.java

public void loadHttpMethod(final ClientRequest request, HttpRequestBase httpMethod) throws Exception {
    if (httpMethod instanceof HttpGet && request.followRedirects()) {
        HttpClientParams.setRedirecting(httpMethod.getParams(), true);
    } else {//from  w w  w. j ava2 s.c o m
        HttpClientParams.setRedirecting(httpMethod.getParams(), false);
    }

    if (request.getBody() != null && !request.getFormParameters().isEmpty())
        throw new RuntimeException("You cannot send both form parameters and an entity body");

    if (!request.getFormParameters().isEmpty()) {
        commitHeaders(request, httpMethod);
        HttpPost post = (HttpPost) httpMethod;

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        for (Map.Entry<String, List<String>> formParam : request.getFormParameters().entrySet()) {
            List<String> values = formParam.getValue();
            for (String value : values) {
                formparams.add(new BasicNameValuePair(formParam.getKey(), value));
            }
        }

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
        post.setEntity(entity);
    } else if (request.getBody() != null) {
        if (httpMethod instanceof HttpGet)
            throw new RuntimeException("A GET request cannot have a body.");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            request.writeRequestBody(request.getHeadersAsObjects(), baos);
            ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray()) {
                @Override
                public Header getContentType() {
                    return new BasicHeader("Content-Type", request.getBodyContentType().toString());
                }
            };
            HttpPost post = (HttpPost) httpMethod;
            commitHeaders(request, httpMethod);
            post.setEntity(entity);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else // no body
    {
        commitHeaders(request, httpMethod);
    }
}

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java

/**
 * Deletes a classifier.//www. j a v a  2  s  .  co m
 * 
 * @param classifierId
 *            the classifier ID
 * @throws UnsupportedEncodingException 
 * @see Classifier
 */
public void deleteClassifier(String classifierId) throws UnsupportedEncodingException {
    if (classifierId == null || classifierId.isEmpty())
        throw new IllegalArgumentException("classifierId can not be null or empty");

    HttpRequestBase request = Request.Delete("/v1/classifiers/" + classifierId).build();
    HttpHost proxy = new HttpHost("10.100.1.124", 3128);
    ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
    executeWithoutResponse(request);
}

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java

/**
 * Retrieves a classifier.//from   w  ww .  j  a  v  a 2 s .  c o m
 * 
 * @param classifierId
 *            the classifier ID
 * @return the classifier list
 * @throws UnsupportedEncodingException 
 * @see Classifier
 */
public Classifier getClassifier(String classifierId) throws UnsupportedEncodingException {
    if (classifierId == null || classifierId.isEmpty())
        throw new IllegalArgumentException("classifierId can not be null or empty");

    HttpRequestBase request = Request.Get("/v1/classifiers/" + classifierId).build();
    HttpHost proxy = new HttpHost("10.100.1.124", 3128);
    ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
    try {
        HttpResponse response = execute(request);
        return ResponseUtil.getObject(response, Classifier.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java

/**
 * Sends data to create and train a classifier, and returns information about the new
 * classifier. The status has the value of `Training` when the operation is
 * successful, and might remain at this status for a while.
 *
 * @param name            the classifier name
 * @param language            IETF primary language for the classifier
 * @param csvTrainingData the CSV training data
 * @return the classifier/*from   w  ww .  j a  va 2s  .  c om*/
 * @see Classifier
 */
public Classifier createClassifier(final String name, final String language, final File csvTrainingData) {
    if (csvTrainingData == null || !csvTrainingData.exists())
        throw new IllegalArgumentException("csvTrainingData can not be null or not be found");

    JsonObject contentJson = new JsonObject();

    contentJson.addProperty("language", language == null ? LANGUAGE_EN : language);

    if (name != null && !name.isEmpty()) {
        contentJson.addProperty("name", name);
    }

    try {

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("training_data", new FileBody(csvTrainingData));
        reqEntity.addPart("training_metadata", new StringBody(contentJson.toString()));

        HttpRequestBase request = Request.Post("/v1/classifiers").withEntity(reqEntity).build();
        HttpHost proxy = new HttpHost("10.100.1.124", 3128);
        ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
        HttpResponse response = execute(request);
        return ResponseUtil.getObject(response, Classifier.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java

/**
 * Sends data to create and train a classifier, and returns information about the new
 * classifier. The status has the value of `Training` when the operation is
 * successful, and might remain at this status for a while.
 * //from  www . j a  v  a  2  s.  c om
 * @param name
 *            the classifier name
 * @param language
 *            IETF primary language for the classifier
 * @param trainingData
 *            The set of questions and their "keys" used to adapt a system to a domain
 *            (the ground truth)
 * @return the classifier
 * @see Classifier
 */
public Classifier createClassifier(final String name, final String language,
        final List<TrainingData> trainingData) {
    if (trainingData == null || trainingData.isEmpty())
        throw new IllegalArgumentException("trainingData can not be null or empty");

    JsonObject contentJson = new JsonObject();

    contentJson.addProperty("language", language == null ? LANGUAGE_EN : language);

    if (name != null && !name.isEmpty()) {
        contentJson.addProperty("name", name);
    }

    try {

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("training_data",
                new StringBody(TrainingDataUtils.toCSV(trainingData.toArray(new TrainingData[0]))));
        reqEntity.addPart("training_metadata", new StringBody(contentJson.toString()));

        HttpRequestBase request = Request.Post("/v1/classifiers").withEntity(reqEntity).build();
        HttpHost proxy = new HttpHost("10.100.1.124", 3128);
        ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
        HttpResponse response = execute(request);
        return ResponseUtil.getObject(response, Classifier.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.code.jerseyclients.httpclientfour.ApacheHttpClientFourHandler.java

public ClientResponse handle(final ClientRequest clientRequest) throws ClientHandlerException {

    if (this.jerseyHttpClientConfig.getApplicationCode() != null) {
        clientRequest.getHeaders().add(this.jerseyHttpClientConfig.getApplicationCodeHeader(),
                this.jerseyHttpClientConfig.getApplicationCode());
    }//from www.j a v  a2s . c  o  m
    if (this.jerseyHttpClientConfig.getOptionnalHeaders() != null) {
        for (Entry<String, String> entry : this.jerseyHttpClientConfig.getOptionnalHeaders().entrySet()) {
            clientRequest.getHeaders().add(entry.getKey(), entry.getValue());
        }
    }
    // final Map<String, Object> props = cr.getProperties();

    final HttpRequestBase method = getHttpMethod(clientRequest);

    // Set the read timeout
    final Integer readTimeout = jerseyHttpClientConfig.getReadTimeOut();
    if (readTimeout != null) {
        HttpConnectionParams.setSoTimeout(method.getParams(), readTimeout.intValue());
    }

    // FIXME penser au header http
    // DEBUG|wire.header|>> "Cache-Control: no-cache[\r][\n]"
    // DEBUG|wire.header|>> "Pragma: no-cache[\r][\n]"
    if (method instanceof HttpEntityEnclosingRequestBase) {
        final HttpEntityEnclosingRequestBase entMethod = (HttpEntityEnclosingRequestBase) method;

        if (clientRequest.getEntity() != null) {
            final RequestEntityWriter re = getRequestEntityWriter(clientRequest);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                re.writeRequestEntity(new CommittingOutputStream(baos) {
                    @Override
                    protected void commit() throws IOException {
                        writeOutBoundHeaders(clientRequest.getHeaders(), method);
                    }
                });
            } catch (IOException ex) {
                throw new ClientHandlerException(ex);
            }

            final byte[] content = baos.toByteArray();
            HttpEntity httpEntity = new ByteArrayEntity(content);
            entMethod.setEntity(httpEntity);

        }
    } else {
        writeOutBoundHeaders(clientRequest.getHeaders(), method);
    }

    try {
        StopWatch stopWatch = new StopWatch();
        stopWatch.reset();
        stopWatch.start();
        HttpResponse httpResponse = client.execute(method);
        int httpReturnCode = httpResponse.getStatusLine().getStatusCode();
        stopWatch.stop();
        log.info("time to call rest url " + clientRequest.getURI() + ", " + stopWatch.getTime() + " ms");

        if (httpReturnCode == Status.NO_CONTENT.getStatusCode()) {
            return new ClientResponse(httpReturnCode, getInBoundHeaders(httpResponse),
                    IOUtils.toInputStream(""), getMessageBodyWorkers());
        }

        return new ClientResponse(httpReturnCode, getInBoundHeaders(httpResponse),
                httpResponse.getEntity() == null ? IOUtils.toInputStream("")
                        : httpResponse.getEntity().getContent(),
                getMessageBodyWorkers());
    } catch (Exception e) {
        throw new ClientHandlerException(e);
    }
}

From source file:anhttpclient.impl.DefaultWebBrowser.java

/**
 * Makes default initialization of HttpMethodBase before any request
 * such as cookie policy, retrycount, timeout
 *
 * @param httpMethodBase {@link HttpRequestBase} for making default initialization
 *//* www .jav a  2  s  .  c  o m*/
private void setDefaultMethodParams(final HttpRequestBase httpMethodBase) {
    httpMethodBase.getParams().setBooleanParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, true);
    httpMethodBase.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    // We use here DefaultHttpMethodRetryHandler with <b>true</b> parameter
    // because we suppose that if method was successfully sent its headers
    // it could also be retried
    if (AbstractHttpClient.class.isAssignableFrom(httpClient.getClass())) {
        ((AbstractHttpClient) httpClient)
                .setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, true));
    }
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
}

From source file:com.mobeelizer.mobile.android.MobeelizerRealConnectionManager.java

private void setProxyIfNecessary(final HttpRequestBase request) {
    String proxyHost = Proxy.getHost(application.getContext());
    if (proxyHost == null) {
        return;/*www  .  j a v  a  2  s .c  o  m*/
    }

    int proxyPort = Proxy.getPort(application.getContext());
    if (proxyPort < 0) {
        return;
    }

    HttpHost proxy = new HttpHost(proxyHost, proxyPort);
    ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
}