Package org.apache.http.client

Examples of org.apache.http.client.HttpClient


                useDynamicProxy ? proxyHost : PROXY_HOST,
                useDynamicProxy ? proxyPort : PROXY_PORT,
                useDynamicProxy ? getProxyUser() : PROXY_USER,
                useDynamicProxy ? getProxyPass() : PROXY_PASS);
       
        HttpClient httpClient = map.get(key);

        if (httpClient == null){ // One-time init for this client

            HttpParams clientParams = new DefaultedHttpParams(new BasicHttpParams(), DEFAULT_HTTP_PARAMS);
           
            httpClient = new DefaultHttpClient(clientParams){
                @Override
                protected HttpRequestRetryHandler createHttpRequestRetryHandler() {
                    return new DefaultHttpRequestRetryHandler(RETRY_COUNT, false) {
                        // TODO HACK to fix https://issues.apache.org/jira/browse/HTTPCLIENT-1120
                        // can hopefully be removed when 4.1.3 or 4.2 are released
                        @Override
                        public boolean retryRequest(IOException ex, int count, HttpContext ctx) {
                            Object request = ctx.getAttribute(ExecutionContext.HTTP_REQUEST);
                            if(request instanceof HttpUriRequest){
                                if (request instanceof RequestWrapper) {
                                    request = ((RequestWrapper) request).getOriginal();
                                }
                                if(((HttpUriRequest)request).isAborted()){
                                    log.warn("Workround for HTTPCLIENT-1120 request retry: "+ex);
                                    return false;
                                }
                            }
                            /*
                             * When connect fails due to abort, the request is not in the context.
                             * Tried adding the request - with a new key - to the local context in the sample() method,
                             * but the request was not flagged as aborted, so that did not help.
                             * So we check for any specific exception that is triggered.
                             */
                            if (
                                   (ex instanceof java.net.BindException &&
                                    ex.getMessage().contains("Address already in use: connect"))   
                                ||
                                    ex.getMessage().contains("Request aborted") // plain IOException                               
                                ) {
                                /*
                                 * The above messages may be generated by aborted connects.
                                 * If either occurs in other situations, retrying is unlikely to help,
                                 * so preventing retry should not cause a problem.
                                */
                                log.warn("Workround for HTTPCLIENT-1120 connect retry: "+ex);
                                return false;
                            }
                            return super.retryRequest(ex, count, ctx);
                        } // end of hack
                    }; // set retry count
                }
            };
            ((AbstractHttpClient) httpClient).addResponseInterceptor(new ResponseContentEncoding());
            ((AbstractHttpClient) httpClient).addResponseInterceptor(METRICS_SAVER); // HACK
           
            // Override the defualt schemes as necessary
            SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();

            if (SLOW_HTTP != null){
                schemeRegistry.register(SLOW_HTTP);
            }

View Full Code Here


    String layerName = layerInfo.getName();
    String requestString = "request=GetFeature&version=1.1.0&outputFormat=shape-zip";
    requestString += "&typeName=" + workspace + ":" + layerName;
    requestString += "&srsName=EPSG:4326";
    requestString += "&BBOX=" + requestBounds.toString() + ",EPSG:4326";
    HttpClient httpclient = ogpHttpClient.getHttpClient();
    File outputFile = null;
   
      String wfsLocation = ParseJSONSolrLocationField.getWfsUrl(layerInfo.getLocation());
        HttpGet httpget = new HttpGet(wfsLocation + "?" + requestString);

        logger.info("executing request " + httpget.getURI());
       
    try {
      HttpResponse response = httpclient.execute(httpget);
      logger.info("Response code: " + Integer.toString(response.getStatusLine().getStatusCode()));
      if (response.getStatusLine().getStatusCode() != 200){
        throw new Exception("Attempt to download " + layerName + " failed.");
      }
     
View Full Code Here

  public InputStream sendGetRequest(String url) throws MalformedURLException{
    /*if (!checkUrl(url)){
      throw new MalformedURLException();
    }*/
    logger.debug("about to send url: " + url);
    HttpClient httpclient = ogpHttpClient.getHttpClient();
    InputStream replyStream = null;
    try {
      HttpGet httpget = new HttpGet(url);
     
      logger.info("executing get request " + httpget.getURI());

      HttpResponse response = httpclient.execute(httpget);
      this.setStatus(response.getStatusLine().getStatusCode());
      this.setHeaders(response.getAllHeaders());
      HttpEntity entity = response.getEntity();
      this.setContentType(entity.getContentType().getValue());
     
View Full Code Here

    return sendRequest(serviceURL, requestString, requestMethod, "text/xml");
  }

  protected InputStream sendPostRequest(String serviceURL,
      String requestBody, String contentType) {
    HttpClient httpclient = ogpHttpClient.getHttpClient();
    InputStream replyStream = null;
    try {
      HttpPost httppost = new HttpPost(serviceURL);
      logger.debug(requestBody);
      StringEntity postEntity = new StringEntity(requestBody, ContentType.create(contentType, "UTF-8"));
      httppost.setEntity(postEntity);
      logger.info("executing POST request to " + httppost.getURI());
      HttpResponse response = httpclient.execute(httppost);
      this.setStatus(response.getStatusLine().getStatusCode());
      this.setHeaders(response.getAllHeaders());
      HttpEntity entity = response.getEntity();
     
      this.setContentType(entity.getContentType().getValue());
View Full Code Here

      HttpServletResponse response, String remoteUrl){
    this.abstractRequest(request, response, remoteUrl, "copy");
  }
 
  public void abstractRequest(HttpServletRequest request, HttpServletResponse response, String remoteUrl, String action){
    HttpClient httpclient = ogpHttpClient.getHttpClient();
    try {

      HttpGet internalRequest = new HttpGet(remoteUrl);
      HttpResponse internalResponse = httpclient.execute(internalRequest);

      this.checkStatus(internalResponse, response);

      if (action.equalsIgnoreCase("copy")){
        this.copyResponse(internalResponse, response);
View Full Code Here

    }
  }
 
  public void abstractRequest(HttpServletRequest request, HttpServletResponse response, String remoteAddress, String action){
    HttpHost targetHost = new HttpHost(remoteAddress);
    HttpClient httpclient = this.ogpHttpClient.getHttpClient();
   
    if (useAuthentication){
      int port = targetHost.getPort();
      String hostName = targetHost.getHostName();
   
      this.credentials = new UsernamePasswordCredentials(this.username, this.password);
//this may not work.  may need a new client.
      ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(
              new AuthScope(hostName, port),
              this.credentials);
     
      // Create AuthCache instance
      AuthCache authCache = new BasicAuthCache();
      // Generate BASIC scheme object and add it to the local auth cache
      BasicScheme basicAuth = new BasicScheme();
   
      authCache.put(targetHost, basicAuth);

      // Add AuthCache to the execution context
      BasicHttpContext localcontext = new BasicHttpContext();
      localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }
   
    try {

      HttpGet internalRequest = new HttpGet(remoteAddress);
      HttpResponse internalResponse = httpclient.execute(internalRequest);
      //internalResponse.getEntity().getContent()
      // copy headers
      //this.copyHeaders(internalResponse, response);

      this.checkStatus(internalResponse, response);

      if (action.equalsIgnoreCase("copy")){
        this.copyResponse(internalResponse, response);
      } else if (action.equalsIgnoreCase("stream")){
        responseEntity = internalResponse.getEntity();
      }
   
     
    } catch (Exception e){
      System.out.println("generic proxy failed");
      System.out.println(e.getMessage());
      try {
        response.getOutputStream().print(e.getMessage());
      } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }
      e.getStackTrace();
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpclient.getConnectionManager().shutdown();
    }
  }
View Full Code Here

            sslsf.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            for (String connectstring : getConnectorStrings("https_proxy")) {
                HttpGet request = new HttpGet(connectstring + "/proxy/reload");


                HttpClient httpClient = new org.apache.http.impl.client.DefaultHttpClient();
                String[] parts = connectstring.split(":");
                httpClient.getConnectionManager().getSchemeRegistry().register(new org.apache.http.conn.scheme.Scheme("https", Integer.parseInt(parts[parts.length - 1]), sslsf));
                HttpResponse response = httpClient.execute(request);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("Exception caught during proxy reload.  Things may be in an inconsistent state.");
        }
View Full Code Here

  private static Map<String, Object> executeMethod(HttpUriRequest httpUriRequest, String url, String body, Integer connectionTimeout, Integer soTimeout)
  {
    HashMap<String, Object> map = new HashMap<String, Object>();
    try
    {
      HttpClient client = getHttpClient(url, connectionTimeout, soTimeout);
      httpUriRequest.setHeader("Accept", "application/json");
      if (url.contains("/Cards/card/search"))
        url = truncData(url);
      long t1 = System.currentTimeMillis();
      HttpResponse response = client.execute(httpUriRequest);
      long t2 = System.currentTimeMillis();
      NewRelic.addCustomParameter(System.currentTimeMillis()+"--"+url, (t2 - t1) + " ms");
      HttpEntity resEntity = response.getEntity();
      String contentCharSet = EntityUtils.getContentCharSet(resEntity);
      map.put("status", response.getStatusLine().getStatusCode());
View Full Code Here

  private static Map<String, Object> executeMethod(HttpUriRequest httpUriRequest, String url, String body, Integer connectionTimeout, Integer soTimeout)
  {
    HashMap<String, Object> map = new HashMap<String, Object>();
    try
    {
      HttpClient client = getHttpClient(url, connectionTimeout, soTimeout);
      httpUriRequest.setHeader("Accept", "application/json");
      if (url.contains("/Cards/card/search"))
        url = truncData(url);
      long t1 = System.currentTimeMillis();
      HttpResponse response = client.execute(httpUriRequest);
      long t2 = System.currentTimeMillis();
      NewRelic.addCustomParameter(System.currentTimeMillis()+"--"+url, (t2 - t1) + " ms");
      HttpEntity resEntity = response.getEntity();
      String contentCharSet = EntityUtils.getContentCharSet(resEntity);
      map.put("status", response.getStatusLine().getStatusCode());
View Full Code Here

public class ProviderClient
{
  public static Map<String, Object> post(String url, Map<String, Object> body, Integer connectionTimeout, Integer soTimeout) throws Exception
  {
    HttpClient client = getHttpClient(url, connectionTimeout, soTimeout);
    HttpPost httppost = new HttpPost(url);
    List<NameValuePair> formParams = setParams(httppost, body);
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
    httppost.setEntity(entity);
    long t1 = System.currentTimeMillis();
    HttpResponse response = client.execute(httppost);
    long t2 = System.currentTimeMillis();
    NewRelic.addCustomParameter(System.currentTimeMillis()+"--"+url, (t2 - t1) + " ms");
    HttpEntity resEntity = response.getEntity();
    String contentCharSet = EntityUtils.getContentCharSet(resEntity);
    HashMap<String, Object> map = new HashMap<String, Object>();
View Full Code Here

TOP

Related Classes of org.apache.http.client.HttpClient

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.