Example usage for org.apache.http.impl.client DefaultHttpClient getParams

List of usage examples for org.apache.http.impl.client DefaultHttpClient getParams

Introduction

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

Prototype

public synchronized final HttpParams getParams() 

Source Link

Usage

From source file:org.xwiki.extension.repository.xwiki.internal.resources.ExtensionVersionFileRESTResource.java

private ResponseBuilder downloadLocalExtension(String extensionId, String extensionVersion)
        throws ResolveException, IOException, QueryException, XWikiException {
    XWikiDocument extensionDocument = getExistingExtensionDocumentById(extensionId);

    checkRights(extensionDocument);// w w  w.  j  ava 2 s  .co m

    BaseObject extensionObject = getExtensionObject(extensionDocument);
    BaseObject extensionVersionObject = getExtensionVersionObject(extensionDocument, extensionVersion);

    ResponseBuilder response = null;

    ResourceReference resourceReference = this.repositoryManager.getDownloadReference(extensionDocument,
            extensionVersionObject);

    if (ResourceType.ATTACHMENT.equals(resourceReference.getType())) {
        // It's an attachment
        AttachmentReference attachmentReference = this.attachmentResolver
                .resolve(resourceReference.getReference(), extensionDocument.getDocumentReference());

        XWikiContext xcontext = getXWikiContext();

        XWikiDocument document = xcontext.getWiki().getDocument(attachmentReference.getDocumentReference(),
                xcontext);

        checkRights(document);

        XWikiAttachment xwikiAttachment = document.getAttachment(attachmentReference.getName());

        response = getAttachmentResponse(xwikiAttachment);
    } else if (ResourceType.URL.equals(resourceReference.getType())) {
        // It's an URL
        URL url = new URL(resourceReference.getReference());

        DefaultHttpClient httpClient = new DefaultHttpClient();

        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "XWikiExtensionRepository");
        httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
        httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        httpClient.setRoutePlanner(routePlanner);

        HttpGet getMethod = new HttpGet(url.toString());

        HttpResponse subResponse;
        try {
            subResponse = httpClient.execute(getMethod);
        } catch (Exception e) {
            throw new IOException("Failed to request [" + getMethod.getURI() + "]", e);
        }

        response = Response.status(subResponse.getStatusLine().getStatusCode());

        // TODO: find a proper way to do a perfect proxy of the URL without directly using Restlet classes.
        // Should probably use javax.ws.rs.ext.MessageBodyWriter
        HttpEntity entity = subResponse.getEntity();
        InputRepresentation content = new InputRepresentation(entity.getContent(),
                new MediaType(entity.getContentType().getValue()), entity.getContentLength());

        String type = getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_TYPE);

        Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT);
        disposition.setFilename(extensionId + '-' + extensionVersion + '.' + type);
        content.setDisposition(disposition);

        response.entity(content);
    } else if (ExtensionResourceReference.TYPE.equals(resourceReference.getType())) {
        ExtensionResourceReference extensionResource;
        if (resourceReference instanceof ExtensionResourceReference) {
            extensionResource = (ExtensionResourceReference) resourceReference;
        } else {
            extensionResource = new ExtensionResourceReference(resourceReference.getReference());
        }

        response = downloadRemoteExtension(extensionResource);
    } else {
        throw new WebApplicationException(Status.NOT_FOUND);
    }

    return response;
}

From source file:ilarkesto.integration.max.internet.RequestExecutor.java

public RequestExecutor(DefaultHttpClient httpClient) {
    this.httpClient = httpClient;
    // HttpProtocolParams.setUserAgent(httpClient.getParams(),
    // "Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
    HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
}

From source file:org.xmetdb.rest.protocol.attachments.CallableAttachmentImporter.java

protected HttpClient createHTTPClient(String hostName, int port) {
    DefaultHttpClient cli = new DefaultHttpClient();
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);/*ww w  . j av a2 s .  c  om*/
    cli.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    cli.getCredentialsProvider().setCredentials(new AuthScope(hostName, port), creds);
    ((DefaultHttpClient) cli).addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            //if (ssoToken != null)
            //request.addHeader("subjectid",ssoToken.getToken());
        }
    });
    return cli;
}

From source file:com.google.acre.servlet.ProxyPassServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse An object by which we can send the proxied
 *                             response back to the client
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 *//*from   w ww  . j av a  2 s . c om*/
private void executeProxyRequest(HttpRequestBase httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    String proxy_host = Configuration.Values.HTTP_PROXY_HOST.getValue();
    int proxy_port = -1;
    if (!(proxy_host.length() == 0)) {
        proxy_port = Configuration.Values.HTTP_PROXY_PORT.getInteger();
        HttpHost proxy = new HttpHost(proxy_host, proxy_port, "http");
        client.getParams().setParameter(AllClientPNames.DEFAULT_PROXY, proxy);
    }

    // Execute the request
    HttpResponse res = client.execute(httpMethodProxyRequest);
    int rescode = res.getStatusLine().getStatusCode();

    // Pass response headers back to the client
    Header[] headerArrayResponse = res.getAllHeaders();
    for (Header header : headerArrayResponse) {
        httpServletResponse.addHeader(header.getName(), header.getValue());
    }

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (rescode >= 300 && rescode < 304) {
        String stringStatusCode = Integer.toString(rescode);
        String stringLocation = httpMethodProxyRequest.getFirstHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Recieved status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(
                stringLocation.replace(this.metawebAPIHostAndPort + this.metawebAPIPath, stringMyHostName));
        return;
    } else if (rescode == 304) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(304);
        return;
    }

    httpServletResponse.setStatus(rescode);

    InputStream instream = new BufferedInputStream(res.getEntity().getContent());
    OutputStream outstream = httpServletResponse.getOutputStream();
    IOUtils.copy(instream, outstream);
    instream.close();
}

From source file:org.mariotaku.twidere.util.httpclient.HttpClientImpl.java

public HttpClientImpl(final HttpClientConfiguration conf) {
    this.conf = conf;
    final SchemeRegistry registry = new SchemeRegistry();
    final SSLSocketFactory factory = conf.isSSLErrorIgnored() ? TRUST_ALL_SSL_SOCKET_FACTORY
            : SSLSocketFactory.getSocketFactory();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", factory, 443));
    final HttpParams params = new BasicHttpParams();
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
    final DefaultHttpClient client = new DefaultHttpClient(cm, params);
    final HttpParams client_params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(client_params, conf.getHttpConnectionTimeout());
    HttpConnectionParams.setSoTimeout(client_params, conf.getHttpReadTimeout());

    if (conf.getHttpProxyHost() != null && !conf.getHttpProxyHost().equals("")) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        if (conf.getHttpProxyUser() != null && !conf.getHttpProxyUser().equals("")) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(//from   w  w  w .  ja v a  2  s.c o m
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
        }
    }
    this.client = client;
}

From source file:com.dwdesign.tweetings.util.httpclient.HttpClientImpl.java

public HttpClientImpl(final HttpClientConfiguration conf) {
    this.conf = conf;
    final SchemeRegistry registry = new SchemeRegistry();
    //final SSLSocketFactory factory = conf.isSSLErrorIgnored() ? TRUST_ALL_SSL_SOCKET_FACTORY : SSLSocketFactory
    //   .getSocketFactory();
    final SSLSocketFactory factory = TRUST_ALL_SSL_SOCKET_FACTORY;
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", factory, 443));
    final HttpParams params = new BasicHttpParams();
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
    final DefaultHttpClient client = new DefaultHttpClient(cm, params);
    final HttpParams client_params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(client_params, conf.getHttpConnectionTimeout());
    HttpConnectionParams.setSoTimeout(client_params, conf.getHttpReadTimeout());

    if (conf.getHttpProxyHost() != null && !conf.getHttpProxyHost().equals("")) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        if (conf.getHttpProxyUser() != null && !conf.getHttpProxyUser().equals("")) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug("Proxy AuthPassword: "
                        + z_T4JInternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }/*from  w w w.j a  va 2  s .c o  m*/
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
        }
    }
    this.client = client;
}

From source file:org.mariotaku.twidere.util.net.HttpClientImpl.java

public HttpClientImpl(final HttpClientConfiguration conf) {
    this.conf = conf;
    final SchemeRegistry registry = new SchemeRegistry();
    final SSLSocketFactory factory = conf.isSSLErrorIgnored() ? TRUST_ALL_SSL_SOCKET_FACTORY
            : SSLSocketFactory.getSocketFactory();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", factory, 443));
    final HttpParams params = new BasicHttpParams();
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
    final DefaultHttpClient client = new DefaultHttpClient(cm, params);
    final HttpParams clientParams = client.getParams();
    HttpConnectionParams.setConnectionTimeout(clientParams, conf.getHttpConnectionTimeout());
    HttpConnectionParams.setSoTimeout(clientParams, conf.getHttpReadTimeout());

    if (conf.getHttpProxyHost() != null && !conf.getHttpProxyHost().equals("")) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        if (conf.getHttpProxyUser() != null && !conf.getHttpProxyUser().equals("")) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(/*ww  w  .j a  v  a  2s  .  c  o  m*/
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
        }
    }
    this.client = client;
}

From source file:fast.servicescreen.server.RequestServiceImpl.java

/**
 * This method receive a requestURL, a hash map within header names and values and
 * a body./*from w w  w  . j av a 2 s  .  c o  m*/
 * 
 *  TODO dk currently this works for SOAP requests.. get it work for nbormal POST, too
 * */
@Override
public String sendHttpRequest_POST(String url, HashMap<String, String> headers, String body) {
    //create client and method appending to url
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpProtocolParams.setUseExpectContinue(httpclient.getParams(), false);
    HttpPost post = new HttpPost(url);

    //adds the given header
    addHeader(post, headers);

    String result = "";
    try {
        HttpEntity entity = new StringEntity(body);
        post.setEntity(entity);

        HttpResponse response = httpclient.execute(post);

        HttpEntity r_entity = response.getEntity();

        if (r_entity != null) {
            int sign = 0;
            InputStream inStream = r_entity.getContent();

            while ((sign = inStream.read()) > -1) {
                result += new String(new byte[] { (byte) sign });
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    //delete connection
    httpclient.getConnectionManager().shutdown();

    return result;
}