Example usage for org.apache.http.params HttpParams setParameter

List of usage examples for org.apache.http.params HttpParams setParameter

Introduction

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

Prototype

HttpParams setParameter(String str, Object obj);

Source Link

Usage

From source file:com.android.picasaphotouploader.ImageUploader.java

/**
 * Upload image to Picasa/*  w  w  w  . j  a  va  2  s .  co  m*/
 */
public void run() {
    // create items for http client
    UploadNotification notification = new UploadNotification(context, item.imageId, item.imageSize,
            item.imageName);
    String url = "http://picasaweb.google.com/data/feed/api/user/" + item.prefs.getString("email", "")
            + "/albumid/" + item.prefs.getString("album", "");
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    try {
        // new file and and entity
        File file = new File(item.imagePath);
        Multipart multipart = new Multipart("Media multipart posting", "END_OF_PART");

        // create entity parts
        multipart.addPart("<entry xmlns='http://www.w3.org/2005/Atom'><title>" + item.imageName
                + "</title><category scheme=\"http://schemas.google.com/g/2005#kind\" term=\"http://schemas.google.com/photos/2007#photo\"/></entry>",
                "application/atom+xml");
        multipart.addPart(file, item.imageType);

        // create new Multipart entity
        MultipartNotificationEntity entity = new MultipartNotificationEntity(multipart, notification);

        // get http params
        HttpParams params = client.getParams();

        // set protocal and timeout for httpclient
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(15000));
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(15000));

        // set body with upload entity
        post.setEntity(entity);

        // set headers
        post.addHeader("Authorization", "GoogleLogin auth=" + item.imageAuth);
        post.addHeader("GData-Version", "2");
        post.addHeader("MIME-version", "1.0");

        // execute upload to picasa and get response and status
        HttpResponse response = client.execute(post);
        StatusLine line = response.getStatusLine();

        // return code indicates upload failed so throw exception
        if (line.getStatusCode() > 201) {
            throw new Exception("Failed upload");
        }

        // shut down connection
        client.getConnectionManager().shutdown();

        // notify user that file has been uploaded
        notification.finished();
    } catch (Exception e) {
        // file upload failed so abort post and close connection
        post.abort();
        client.getConnectionManager().shutdown();

        // get user preferences and number of retries for failed upload
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        int maxRetries = Integer.valueOf(prefs.getString("retries", "").substring(1));

        // check if we can connect to internet and if we still have any tries left
        // to try upload again
        if (CheckInternet.getInstance().canConnect(context, prefs) && retries < maxRetries) {
            // remove notification for failed upload and queue item again
            notification.remove();
            queue.execute(new ImageUploader(context, queue, item, retries++));
        } else {
            // upload failed, so let's notify user
            notification.failed();
        }
    }
}

From source file:de.uzk.hki.da.webservice.HttpFileTransmissionClient.java

/**
 * Cleanup.//from  w  ww . ja v a2s. com
 *
 * @throws ClientProtocolException the client protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void cleanup() {
    HttpClient httpclient = null;
    try {
        httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet(url);
        HttpParams httpRequestParameters = httpget.getParams();
        httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        httpget.setParams(httpRequestParameters);
        java.net.URI uri = new URIBuilder(httpget.getURI()).addParameter("cleanup", "1").build();
        logger.debug("calling webservice for cleanup now. recieving response");
        httpget.setURI(uri);

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity resEntity = response.getEntity();
        printResponse(resEntity);
    } catch (Exception e) {
        logger.error("Exception occured in cleanup " + e.getStackTrace());
        throw new RuntimeException("Webservice error " + url, e);
    } finally {
        if (httpclient != null)
            httpclient.getConnectionManager().shutdown();
    }
}

From source file:pl.psnc.synat.wrdz.zmkd.invocation.RestServiceCaller.java

/**
 * Invoke a service according to the execution info.
 * /*from  w ww  .  j ava  2 s  .c  o  m*/
 * In case of success, the entity stream is not closed.
 * 
 * @param execInfo
 *            info how to execute a REST service
 * @return execution outcome
 * @throws InvalidHttpRequestException
 *             when constructed request is invalid
 * @throws InvalidHttpResponseException
 *             when response is invalid
 */
public ExecutionOutcome invoke(ExecutionInfo execInfo)
        throws InvalidHttpRequestException, InvalidHttpResponseException {
    HttpClient httpClient = getHttpClient();
    HttpRequestBase request = null;
    try {
        request = RestServiceCallerUtils.constructServiceRequestBase(execInfo);
    } catch (URISyntaxException e) {
        logger.error("Incorrect URI of the service.", e);
        throw new InvalidHttpRequestException(e);
    }
    if (request instanceof HttpEntityEnclosingRequestBase) {
        HttpEntity entity = RestServiceCallerUtils.constructServiceRequestEntity(execInfo);
        if (entity != null) {
            ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
        }
        Header header = RestServiceCallerUtils.constructServiceRequestHeader(execInfo);
        if (header != null) {
            request.setHeader(header);
        }
    }

    HttpParams params = new BasicHttpParams();
    params.setParameter("http.protocol.handle-redirects", false);
    request.setParams(params);

    HttpResponse response = null;
    try {
        response = httpClient.execute(request);
    } catch (ClientProtocolException e) {
        logger.error("Incorrect protocol.", e);
        throw new InvalidHttpResponseException(e);
    } catch (IOException e) {
        logger.error("IO error during execution.", e);
        throw new InvalidHttpResponseException(e);
    }
    try {
        return RestServiceCallerUtils.retrieveOutcome(response);
    } catch (IllegalStateException e) {
        logger.error("Cannot retrived the stream with the content.", e);
        EntityUtils.consumeQuietly(response.getEntity());
        throw new InvalidHttpResponseException(e);
    } catch (IOException e) {
        logger.error("IO error when retrieving content.", e);
        EntityUtils.consumeQuietly(response.getEntity());
        throw new InvalidHttpResponseException(e);
    }
    // remember to close the entity stream after read it.  
}

From source file:com.cloudant.client.org.lightcouch.CouchDbClientAndroid.java

/**
 * @return {@link DefaultHttpClient} instance.
 *//*from w w  w  . j av a  2  s . c o m*/
@Override
HttpClient createHttpClient(CouchDbProperties props) {
    DefaultHttpClient httpclient = null;
    try {
        final SchemeRegistry schemeRegistry = createRegistry(props);
        // Http params
        final HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout());
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, props.getConnectionTimeout());
        final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager(params, schemeRegistry);
        httpclient = new DefaultHttpClient(ccm, params);
        if (props.getProxyHost() != null) {
            HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        // basic authentication
        if (props.getUsername() != null && props.getPassword() != null) {
            httpclient.getCredentialsProvider().setCredentials(new AuthScope(props.getHost(), props.getPort()),
                    new UsernamePasswordCredentials(props.getUsername(), props.getPassword()));
            props.clearPassword();
        }
        registerInterceptors(httpclient);
    } catch (Exception e) {
        throw new IllegalStateException("Error Creating HTTP client. ", e);
    }
    return httpclient;
}

From source file:gov.nasa.arc.geocam.memo.service.SiteAuthCookieImplementation.java

@Override
public int post(String relativePath, Map<String, String> params)
        throws AuthenticationFailedException, IOException, ClientProtocolException {
    ensureAuthenticated();/*from  www .j  av  a  2  s  . co m*/

    httpClient = new DefaultHttpClient();
    HttpParams httpParams = httpClient.getParams();
    HttpClientParams.setRedirecting(httpParams, false);
    httpParams.setParameter("http.protocol.handle-redirects", false);

    HttpPost post = new HttpPost(this.serverRootUrl + "/" + appPath + "/" + relativePath);
    post.setParams(httpParams);

    if (params != null) {
        List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
        for (String key : params.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
        }

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.ASCII));
    }

    httpClient.getCookieStore().addCookie(sessionIdCookie);
    //post.setHeader("Cookie", sessionIdCookie.toString());

    HttpResponse r = httpClient.execute(post);
    // TODO: check for redirect to login and call login if is the case

    return r.getStatusLine().getStatusCode();
}

From source file:org.fourthline.cling.transport.impl.apache.StreamClientImpl.java

protected HttpParams getRequestParams(StreamRequestMessage requestMessage) {
    HttpParams localParams = new BasicHttpParams();

    localParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
            requestMessage.getOperation().getHttpMinorVersion() == 0 ? HttpVersion.HTTP_1_0
                    : HttpVersion.HTTP_1_1);

    // DefaultHttpClient adds HOST header automatically in its default processor

    // Add the default user agent if not already set on the message
    if (!requestMessage.getHeaders().containsKey(UpnpHeader.Type.USER_AGENT)) {
        HttpProtocolParams.setUserAgent(localParams, getConfiguration()
                .getUserAgentValue(requestMessage.getUdaMajorVersion(), requestMessage.getUdaMinorVersion()));
    }// w  w w .j  a  v  a2s  . c  o  m

    return new DefaultedHttpParams(localParams, globalParams);
}

From source file:com.dhenton9000.filedownloader.FileDownloader.java

private HttpResponse getHTTPResponse() throws IOException, NullPointerException {
    if (fileURI == null)
        throw new NullPointerException("No file URI specified");

    HttpClient client = new DefaultHttpClient();
    BasicHttpContext localContext = new BasicHttpContext();

    //Clear down the local cookie store every time to make sure we don't have any left over cookies influencing the test
    localContext.setAttribute(ClientContext.COOKIE_STORE, null);

    LOG.info("Mimic WebDriver cookie state: " + mimicWebDriverCookieState);
    if (mimicWebDriverCookieState) {
        localContext.setAttribute(ClientContext.COOKIE_STORE, mimicCookieState(driver.manage().getCookies()));
    }//  w ww.  j a  va2s  .co m

    HttpRequestBase requestMethod = httpRequestMethod.getRequestMethod();
    requestMethod.setURI(fileURI);
    HttpParams httpRequestParameters = requestMethod.getParams();
    httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects);
    requestMethod.setParams(httpRequestParameters);
    //TODO if post send map of variables, also need to add a post map setter

    LOG.info("Sending " + httpRequestMethod.toString() + " request for: " + fileURI);
    return client.execute(requestMethod, localContext);
}

From source file:com.catchoom.api.Catchoom.java

public Catchoom() {
    HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    mHttpClient = new DefaultHttpClient(httpParams);
}

From source file:org.jvoicexml.documentserver.schemestrategy.HttpSchemeStrategy.java

/**
 * Sets the timeout for the current connection.
 * /*from  w ww .java 2 s . com*/
 * @param timeout
 *            timeout as it is declared in the document.
 * @param params
 *            connection parameters.
 * @since 0.7
 */
private void setTimeout(final long timeout, final HttpParams params) {
    if (timeout != 0) {
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer((int) timeout));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("timeout set to '" + timeout + "'");
        }
    } else if (defaultFetchTimeout != 0) {
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, defaultFetchTimeout);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("timeout set to default '" + defaultFetchTimeout + "'");
        }
    }
}