Java Code Examples for org.apache.commons.httpclient.HttpClient

The following are top voted examples for showing how to use org.apache.commons.httpclient.HttpClient. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: logistimo-web-service   File: LogiURLFetchService.java   Source Code and License 11 votes vote down vote up
@Override
public HttpResponse get(URL urlObj, String userName, String password, int timeout) {
  HttpClient client = new HttpClient();
  HttpMethod method = new GetMethod(urlObj.toString());

  client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
      new DefaultHttpMethodRetryHandler());
  client.getParams().setSoTimeout(1000 * timeout);
  client.getParams().setConnectionManagerTimeout(1000 * timeout);
  if (userName != null && password != null) {
    setBasicAuthorization(method, userName, password);
  }
  try {
    int response = client.executeMethod(method);
    return new HttpResponse(response, method.getResponseBody());
  } catch (IOException e) {
    throw new RuntimeException("Failed to get " + urlObj.toString(), e);
  } finally {
    method.releaseConnection();
  }
}
 
Example 2
Project: Hydrograph   File: HydrographServiceClient.java   Source Code and License 10 votes vote down vote up
public void chcekConnectionStatus() throws IOException {

        HttpClient httpClient = new HttpClient();
        //TODO : add connection details while testing only,remove it once done
        String teradatajson = "{\"username\":\"\",\"password\":\"\",\"hostname\":\"\",\"database\":\"\",\"dbtype\":\"\",\"port\":\"\"}";
        PostMethod postMethod = new PostMethod("http://" + HOST_NAME + ":" + PORT + "/getConnectionStatus");

        //postMethod.addParameter("request_parameters", redshiftjson);
        postMethod.addParameter("request_parameters", teradatajson);

        int response = httpClient.executeMethod(postMethod);
        InputStream inputStream = postMethod.getResponseBodyAsStream();

        byte[] buffer = new byte[1024 * 1024 * 5];
        String path = null;
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            path = new String(buffer);
        }
        System.out.println("Response of service: " + path);
        System.out.println("==================");
    }
 
Example 3
Project: logistimo-web-service   File: LogiURLFetchService.java   Source Code and License 7 votes vote down vote up
@Override
public HttpResponse post(URL urlObj, byte[] payload, String userName, String password,
                         int timeout) {
  HttpClient client = new HttpClient();
  PostMethod method = new PostMethod(urlObj.toString());
  method.setRequestEntity(new ByteArrayRequestEntity(payload));
  method.setRequestHeader("Content-type", "application/json");
  client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
      new DefaultHttpMethodRetryHandler());
  client.getParams().setSoTimeout(1000 * timeout);
  client.getParams().setConnectionManagerTimeout(1000 * timeout);
  if (userName != null && password != null) {
    setBasicAuthorization(method, userName, password);
  }
  try {
    int response = client.executeMethod(method);
    return new HttpResponse(response, method.getResponseBody());
  } catch (IOException e) {
    throw new RuntimeException("Failed to process post request URL: " + urlObj, e);
  } finally {
    method.releaseConnection();
  }

}
 
Example 4
Project: Spring-Boot-Server   File: HttpUtils.java   Source Code and License 6 votes vote down vote up
public static String getPostResponseHeader(String url,String argJson,List<UHeader> headerList,String headerName){
  	String info = "";
  	try {
   	HttpClient client = new HttpClient();
	PostMethod method = new PostMethod(url);
	client.getParams().setContentCharset("UTF-8");
	if(headerList.size()>0){
		for(int i = 0;i<headerList.size();i++){
			UHeader header = headerList.get(i);
			method.setRequestHeader(header.getHeaderTitle(),header.getHeaderValue());
		}
	}
	method.getParams().setParameter(
			HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
	if(argJson != null && !argJson.trim().equals("")) {
		RequestEntity requestEntity = new StringRequestEntity(argJson,"application/json","UTF-8");
		method.setRequestEntity(requestEntity);
	}
	method.releaseConnection();
	Header h =  method.getResponseHeader(headerName);
	info = h.getValue();
} catch (IOException e) {
	e.printStackTrace();
}
  	return info;
  }
 
Example 5
Project: alfresco-repository   File: HttpClientTransmitterImpl.java   Source Code and License 6 votes vote down vote up
public HttpClientTransmitterImpl()
{
    protocolMap = new TreeMap<String,Protocol>();
    protocolMap.put(HTTP_SCHEME_NAME, httpProtocol);
    protocolMap.put(HTTPS_SCHEME_NAME, httpsProtocol);

    httpClient = new HttpClient();
    httpClient.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
    httpMethodFactory = new StandardHttpMethodFactoryImpl();
    jsonErrorSerializer = new ExceptionJsonSerializer();

    // Create an HTTP Proxy Host if appropriate system properties are set
    httpProxyHost = HttpClientHelper.createProxyHost("http.proxyHost", "http.proxyPort", DEFAULT_HTTP_PORT);
    httpProxyCredentials = HttpClientHelper.createProxyCredentials("http.proxyUser", "http.proxyPassword");
    httpAuthScope = createProxyAuthScope(httpProxyHost);

    // Create an HTTPS Proxy Host if appropriate system properties are set
    httpsProxyHost = HttpClientHelper.createProxyHost("https.proxyHost", "https.proxyPort", DEFAULT_HTTPS_PORT);
    httpsProxyCredentials = HttpClientHelper.createProxyCredentials("https.proxyUser", "https.proxyPassword");
    httpsAuthScope = createProxyAuthScope(httpsProxyHost);
}
 
Example 6
Project: alfresco-repository   File: SolrQueryHTTPClient.java   Source Code and License 6 votes vote down vote up
protected JSONResult postSolrQuery(HttpClient httpClient, String url, JSONObject body, SolrJsonProcessor<?> jsonProcessor, String spellCheckParams)
            throws UnsupportedEncodingException, IOException, HttpException, URIException,
            JSONException
{
    JSONObject json = postQuery(httpClient, url, body);
    if (spellCheckParams != null)
    {
        SpellCheckDecisionManager manager = new SpellCheckDecisionManager(json, url, body, spellCheckParams);
        if (manager.isCollate())
        {
            json = postQuery(httpClient, manager.getUrl(), body);
        }
        json.put("spellcheck", manager.getSpellCheckJsonValue());
    }

        JSONResult results = jsonProcessor.getResult(json);

        if (s_logger.isDebugEnabled())
        {
            s_logger.debug("Sent :" + url);
            s_logger.debug("   with: " + body.toString());
            s_logger.debug("Got: " + results.getNumberFound() + " in " + results.getQueryTime() + " ms");
        }
        
        return results;
}
 
Example 7
Project: alfresco-repository   File: ExplicitSolrStoreMappingWrapper.java   Source Code and License 6 votes vote down vote up
/**
 * @return
 */
public Pair<HttpClient, String> getHttpClientAndBaseUrl()
{

    if (!policy.configurationIsValid())
    {
        throw new AlfrescoRuntimeException("Invalid shard configuration: shard = "
                + wrapped.getNumShards() + "   reoplicationFactor = " + wrapped.getReplicationFactor() + " with node count = " + httpClientsAndBaseURLs.size());
    }
    
    int shard = random.nextInt(wrapped.getNumShards());
    int position =  random.nextInt(wrapped.getReplicationFactor());
    List<Integer> nodeInstances = policy.getNodeInstancesForShardId(shard);
    Integer nodeId = nodeInstances.get(position);         
    HttpClientAndBaseUrl httpClientAndBaseUrl = httpClientsAndBaseURLs.toArray(new HttpClientAndBaseUrl[0])[nodeId-1];
    return new Pair<>(httpClientAndBaseUrl.httpClient, isSharded() ? httpClientAndBaseUrl.baseUrl+"-"+shard : httpClientAndBaseUrl.baseUrl);
}
 
Example 8
Project: automat   File: HttpUtil.java   Source Code and License 6 votes vote down vote up
public static final String httpClientPost(String url, ArrayList<NameValuePair> list) {
	String result = "";
	HttpClient client = new HttpClient();
	PostMethod postMethod = new PostMethod(url);
	try {
		NameValuePair[] params = new NameValuePair[list.size()];
		for (int i = 0; i < list.size(); i++) {
			params[i] = list.get(i);
		}
		postMethod.addParameters(params);
		client.executeMethod(postMethod);
		result = postMethod.getResponseBodyAsString();
	} catch (Exception e) {
		logger.error(e);
	} finally {
		postMethod.releaseConnection();
	}
	return result;
}
 
Example 9
Project: neoscada   File: HdHttpClient.java   Source Code and License 6 votes vote down vote up
public List<DataPoint> getData ( final String item, final String type, final Date from, final Date to, final Integer number ) throws Exception
{
    final HttpClient client = new HttpClient ();
    final HttpMethod method = new GetMethod ( this.baseUrl + "/" + URLEncoder.encode ( item, "UTF-8" ) + "/" + URLEncoder.encode ( type, "UTF-8" ) + "?from=" + URLEncoder.encode ( Utils.isoDateFormat.format ( from ), "UTF-8" ) + "&to=" + URLEncoder.encode ( Utils.isoDateFormat.format ( to ), "UTF-8" ) + "&no=" + number );
    client.getParams ().setSoTimeout ( (int)this.timeout );
    try
    {
        final int status = client.executeMethod ( method );
        if ( status != HttpStatus.SC_OK )
        {
            throw new RuntimeException ( "Method failed with error " + status + " " + method.getStatusLine () );
        }
        return Utils.fromJson ( method.getResponseBodyAsString () );
    }
    finally
    {
        method.releaseConnection ();
    }
}
 
Example 10
Project: alfresco-core   File: HttpClientFactory.java   Source Code and License 6 votes vote down vote up
protected HttpClient constructHttpClient()
{
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpClient httpClient = new HttpClient(connectionManager);
    HttpClientParams params = httpClient.getParams();
    params.setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true);
    params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true);
    if (socketTimeout != null) 
    {
        params.setSoTimeout(socketTimeout);
    }
    HttpConnectionManagerParams connectionManagerParams = httpClient.getHttpConnectionManager().getParams();
    connectionManagerParams.setMaxTotalConnections(maxTotalConnections);
    connectionManagerParams.setDefaultMaxConnectionsPerHost(maxHostConnections);
    connectionManagerParams.setConnectionTimeout(connectionTimeout);

    return httpClient;
}
 
Example 11
Project: alfresco-core   File: HttpClientFactory.java   Source Code and License 6 votes vote down vote up
public HttpClient getHttpClient()
{
    HttpClient httpClient = null;

    if(secureCommsType == SecureCommsType.HTTPS)
    {
        httpClient = getHttpsClient();
    }
    else if(secureCommsType == SecureCommsType.NONE)
    {
        httpClient = getDefaultHttpClient();
    }
    else
    {
        throw new AlfrescoRuntimeException("Invalid Solr secure communications type configured in alfresco.secureComms, should be 'ssl'or 'none'");
    }

    return httpClient;
}
 
Example 12
Project: alfresco-core   File: HttpClientFactory.java   Source Code and License 6 votes vote down vote up
public HttpClient getHttpClient(String host, int port)
{
    HttpClient httpClient = null;

    if(secureCommsType == SecureCommsType.HTTPS)
    {
        httpClient = getHttpsClient(host, port);
    }
    else if(secureCommsType == SecureCommsType.NONE)
    {
        httpClient = getDefaultHttpClient(host, port);
    }
    else
    {
        throw new AlfrescoRuntimeException("Invalid Solr secure communications type configured in alfresco.secureComms, should be 'ssl'or 'none'");
    }

    return httpClient;
}
 
Example 13
Project: jrpip   File: FastServletProxyFactory.java   Source Code and License 6 votes vote down vote up
/**
 * @return the http response code returned from the server. Response code 200 means success.
 */
public static int fastFailPing(AuthenticatedUrl url) throws IOException
{
    PingRequest pingRequest = null;
    try
    {
        HttpClient httpClient = getHttpClient(url);
        pingRequest = new PingRequest(url.getPath());
        HttpMethodParams params = pingRequest.getParams();
        params.setSoTimeout(PING_TIMEOUT);
        httpClient.executeMethod(pingRequest);
        return pingRequest.getStatusCode();
    }
    finally
    {
        if (pingRequest != null)
        {
            pingRequest.releaseConnection();
        }
    }
}
 
Example 14
Project: jrpip   File: FastServletProxyFactory.java   Source Code and License 6 votes vote down vote up
public static HttpClient getHttpClient(AuthenticatedUrl url)
{
    HttpClient httpClient = new HttpClient(HTTP_CONNECTION_MANAGER);
    httpClient.getHostConfiguration().setHost(url.getHost(), url.getPort());
    httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, NoRetryRetryHandler.getInstance());
    url.setCredentialsOnClient(httpClient);
    return httpClient;
}
 
Example 15
Project: jrpip   File: FastServletProxyFactory.java   Source Code and License 6 votes vote down vote up
public static Cookie[] requestNewSession(AuthenticatedUrl url)
{
    CreateSessionRequest createSessionRequest = null;
    try
    {
        HttpClient httpClient = getHttpClient(url);
        createSessionRequest = new CreateSessionRequest(url.getPath());
        HttpMethodParams params = createSessionRequest.getParams();
        params.setSoTimeout(PING_TIMEOUT);
        httpClient.executeMethod(createSessionRequest);
        return httpClient.getState().getCookies();
    }
    catch (Exception e)
    {
        throw new RuntimeException("Failed to create session", e);
    }
    finally
    {
        if (createSessionRequest != null)
        {
            createSessionRequest.releaseConnection();
        }
    }
}
 
Example 16
Project: convertigo-engine   File: PacManager.java   Source Code and License 6 votes vote down vote up
private String downloadPacContent(String url) throws IOException {
	if (url == null) {
		Engine.logProxyManager.debug("(PacManager) Invalid PAC script URL: null");
		throw new IOException("Invalid PAC script URL: null");
	}

	HttpClient client = new HttpClient();
	HttpMethod method = new GetMethod(url);

	int statusCode = client.executeMethod(method);

	if (statusCode != HttpStatus.SC_OK) {
		throw new IOException("(PacManager) Method failed: " + method.getStatusLine());
	}
	
	return IOUtils.toString(method.getResponseBodyAsStream(), "UTF-8");
}
 
Example 17
Project: uavstack   File: HttpService.java   Source Code and License 6 votes vote down vote up
/**
 * 同步客户端3.X版本
 * 
 * @return
 */
@GET
@Path("httpclient3test")
public String httpClient3Test() {

    HttpClient httpClient = new HttpClient();
    HttpMethod method = new GetMethod("https://www.baidu.com/");

    try {
        httpClient.executeMethod(method);
        System.out.println(method.getURI());
        System.out.println(method.getStatusLine());
        System.out.println(method.getName());
        System.out.println(method.getResponseHeader("Server").getValue());
        System.out.println(method.getResponseBodyAsString());
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    return "httpClient3 test success";
}
 
Example 18
Project: convertigo-engine   File: WsReference.java   Source Code and License 6 votes vote down vote up
private static void tryAuthentication(RemoteFileReference wsReference) throws Exception {
	URL urlToConnect = wsReference.getUrl();
	String wsdlUrl = wsReference.getUrlpath();
	String username = wsReference.getAuthUser();
	String password = wsReference.getAuthPassword();
	
       HttpClient client = new HttpClient();

	client.getState().setCredentials(
			new AuthScope(urlToConnect.getHost(), urlToConnect.getPort()),
			new UsernamePasswordCredentials(username, password)
	);
       
       GetMethod get = new GetMethod(wsdlUrl);
       get.setDoAuthentication( true );
       
       int statuscode = client.executeMethod(get);
       
       if (statuscode == HttpStatus.SC_UNAUTHORIZED) {
       	throw new Exception(HttpStatus.SC_UNAUTHORIZED + " - Unauthorized connection!");
       }
}
 
Example 19
Project: lams   File: HTTPMetadataProvider.java   Source Code and License 6 votes vote down vote up
/**
 * Constructor.
 * 
 * @param metadataURL the URL to fetch the metadata
 * @param requestTimeout the time, in milliseconds, to wait for the metadata server to respond
 * 
 * @throws MetadataProviderException thrown if the URL is not a valid URL or the metadata can not be retrieved from
 *             the URL
 */
@Deprecated
public HTTPMetadataProvider(String metadataURL, int requestTimeout) throws MetadataProviderException {
    super();
    try {
        metadataURI = new URI(metadataURL);
    } catch (URISyntaxException e) {
        throw new MetadataProviderException("Illegal URL syntax", e);
    }

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setSoTimeout(requestTimeout);
    httpClient = new HttpClient(clientParams);
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(requestTimeout);
    authScope = new AuthScope(metadataURI.getHost(), metadataURI.getPort());

}
 
Example 20
Project: lams   File: HTTPMetadataProvider.java   Source Code and License 6 votes vote down vote up
/**
 * Constructor.
 * 
 * @param client HTTP client used to pull in remote metadata
 * @param backgroundTaskTimer timer used to schedule background metadata refresh tasks
 * @param metadataURL URL to the remove remote metadata
 * 
 * @throws MetadataProviderException thrown if the HTTP client is null or the metadata URL provided is invalid
 */
public HTTPMetadataProvider(Timer backgroundTaskTimer, HttpClient client, String metadataURL)
        throws MetadataProviderException {
    super(backgroundTaskTimer);

    if (client == null) {
        throw new MetadataProviderException("HTTP client may not be null");
    }
    httpClient = client;

    try {
        metadataURI = new URI(metadataURL);
    } catch (URISyntaxException e) {
        throw new MetadataProviderException("Illegal URL syntax", e);
    }

    authScope = new AuthScope(metadataURI.getHost(), metadataURI.getPort());
}
 
Example 21
Project: iBase4J   File: HttpUtil.java   Source Code and License 6 votes vote down vote up
public static final String httpClientPost(String url, ArrayList<NameValuePair> list) {
	String result = "";
	HttpClient client = new HttpClient();
	PostMethod postMethod = new PostMethod(url);
	try {
		NameValuePair[] params = new NameValuePair[list.size()];
		for (int i = 0; i < list.size(); i++) {
			params[i] = list.get(i);
		}
		postMethod.addParameters(params);
		client.executeMethod(postMethod);
		result = postMethod.getResponseBodyAsString();
	} catch (Exception e) {
		logger.error(e);
	} finally {
		postMethod.releaseConnection();
	}
	return result;
}
 
Example 22
Project: JAVA-   File: HttpUtil.java   Source Code and License 6 votes vote down vote up
public static final String httpClientPost(String url, ArrayList<NameValuePair> list) {
	String result = "";
	HttpClient client = new HttpClient();
	PostMethod postMethod = new PostMethod(url);
	try {
		NameValuePair[] params = new NameValuePair[list.size()];
		for (int i = 0; i < list.size(); i++) {
			params[i] = list.get(i);
		}
		postMethod.addParameters(params);
		client.executeMethod(postMethod);
		result = postMethod.getResponseBodyAsString();
	} catch (Exception e) {
		logger.error(e);
	} finally {
		postMethod.releaseConnection();
	}
	return result;
}
 
Example 23
Project: Hydrograph   File: HydrographServiceClient.java   Source Code and License 6 votes vote down vote up
public void calltoReadMetastore() throws IOException {

        HttpClient httpClient = new HttpClient();
      //TODO : add connection details while testing only,remove it once done
        String teradatajson = "{\"table\":\"testting2\",\"username\":\"\",\"password\":\"\",\"hostname\":\"\",\"database\":\"\",\"dbtype\":\"\",\"port\":\"\"}";

        PostMethod postMethod = new PostMethod("http://" + HOST_NAME + ":" + PORT + "/readFromMetastore");

        //postMethod.addParameter("request_parameters", redshiftjson);
        postMethod.addParameter("request_parameters", teradatajson);

        int response = httpClient.executeMethod(postMethod);
        InputStream inputStream = postMethod.getResponseBodyAsStream();

        byte[] buffer = new byte[1024 * 1024 * 5];
        String path = null;
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            path = new String(buffer);
        }
        System.out.println("Response of service: " + path);
        System.out.println("==================");
    }
 
Example 24
Project: hadoop   File: SwiftRestClient.java   Source Code and License 6 votes vote down vote up
/**
 * Execute the request with the request and response logged at debug level
 * @param method method to execute
 * @param client client to use
 * @param <M> method type
 * @return the status code
 * @throws IOException any failure reported by the HTTP client.
 */
private <M extends HttpMethod> int execWithDebugOutput(M method,
                                                       HttpClient client) throws
        IOException {
  if (LOG.isDebugEnabled()) {
    StringBuilder builder = new StringBuilder(
            method.getName() + " " + method.getURI() + "\n");
    for (Header header : method.getRequestHeaders()) {
      builder.append(header.toString());
    }
    LOG.debug(builder);
  }
  int statusCode = client.executeMethod(method);
  if (LOG.isDebugEnabled()) {
    LOG.debug("Status code = " + statusCode);
  }
  return statusCode;
}
 
Example 25
Project: lib-commons-httpclient   File: MultiThreadedExample.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    
    // Create an HttpClient with the MultiThreadedHttpConnectionManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    // Set the default host/protocol for the methods to connect to.
    // This value will only be used if the methods are not given an absolute URI
    httpClient.getHostConfiguration().setHost("jakarta.apache.org", 80, "http");
    
    // create an array of URIs to perform GETs on
    String[] urisToGet = {
        "/",
        "/commons/",
        "/commons/httpclient/",
        "http://svn.apache.org/viewvc/jakarta/httpcomponents/oac.hc3x/"
    };
    
    // create a thread for each URI
    GetThread[] threads = new GetThread[urisToGet.length];
    for (int i = 0; i < threads.length; i++) {
        GetMethod get = new GetMethod(urisToGet[i]);
        get.setFollowRedirects(true);
        threads[i] = new GetThread(httpClient, get, i + 1);
    }
    
    // start the threads
    for (int j = 0; j < threads.length; j++) {
        threads[j].start();
    }
    
}
 
Example 26
Project: iBase4J-Common   File: HttpUtil.java   Source Code and License 5 votes vote down vote up
public static final String httpClientPost(String url) {
    String result = "";
    HttpClient client = new HttpClient();
    GetMethod getMethod = new GetMethod(url);
    try {
        client.executeMethod(getMethod);
        result = getMethod.getResponseBodyAsString();
    } catch (Exception e) {
        logger.error("", e);
    } finally {
        getMethod.releaseConnection();
    }
    return result;
}
 
Example 27
Project: ditb   File: Client.java   Source Code and License 5 votes vote down vote up
private void initialize(Cluster cluster, boolean sslEnabled) {
  this.cluster = cluster;
  this.sslEnabled = sslEnabled;
  MultiThreadedHttpConnectionManager manager =
    new MultiThreadedHttpConnectionManager();
  HttpConnectionManagerParams managerParams = manager.getParams();
  managerParams.setConnectionTimeout(2000); // 2 s
  managerParams.setDefaultMaxConnectionsPerHost(10);
  managerParams.setMaxTotalConnections(100);
  extraHeaders = new ConcurrentHashMap<String, String>();
  this.httpClient = new HttpClient(manager);
  HttpClientParams clientParams = httpClient.getParams();
  clientParams.setVersion(HttpVersion.HTTP_1_1);

}
 
Example 28
Project: DBus   File: HttpRequest.java   Source Code and License 5 votes vote down vote up
public String doPost(String url, String charset, String jsonObj) {
    String resStr = null;
    HttpClient htpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setParameter(
            HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
    try {
        postMethod.setRequestEntity(new StringRequestEntity(jsonObj,
                "application/json", charset));
        int statusCode = htpClient.executeMethod(postMethod);
        if (statusCode != HttpStatus.SC_OK) {
            // post和put不能自动处理转发 301:永久重定向,告诉客户端以后应从新地址访问 302:Moved
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                Header locationHeader = postMethod
                        .getResponseHeader("location");
                String location = null;
                if (locationHeader != null) {
                    location = locationHeader.getValue();
                    log.info("The page was redirected to :" + location);
                } else {
                    log.info("Location field value is null");
                }
            } else {
                log.error("Method failed: " + postMethod.getStatusLine());
            }
            return resStr;
        }
        byte[] responseBody = postMethod.getResponseBody();
        resStr = new String(responseBody, charset);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        postMethod.releaseConnection();
    }
    return resStr;
}
 
Example 29
Project: lib-commons-httpclient   File: HttpBenchmark.java   Source Code and License 5 votes vote down vote up
private static HttpClient createRequestExecutor() {
    HttpClient httpclient = new HttpClient();
    httpclient.getParams().setVersion(HttpVersion.HTTP_1_1);
    httpclient.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    httpclient.getHttpConnectionManager().getParams().setStaleCheckingEnabled(false);
    return httpclient;
}
 
Example 30
Project: geomapapp   File: Tile512Overlay.java   Source Code and License 5 votes vote down vote up
private static BufferedImage readHTTPImage(URI uri,
		HostConfiguration hostConfiguration, HttpClient client,
		ConnectionWrapper wrapper) {
	List<Proxy> list = ProxySelector.getDefault().select(uri);
	for (Proxy p : list)
	{
		InetSocketAddress addr = (InetSocketAddress) p.address();
		
		if (addr == null)
			hostConfiguration.setProxyHost(null);
		else
			hostConfiguration.setProxy(addr.getHostName(), addr.getPort());
		
		try {
			HttpMethod method = new GetMethod(uri.toString());
			synchronized (wrapper) {
				wrapper.connection = method;
			}
			
			int sc = client.executeMethod(hostConfiguration, method);
			
			if (sc != HttpStatus.SC_OK) {
				continue;
			}
			
			// Check Content Type
			Header h = method.getResponseHeader("Content-Type");
			if (h == null || !h.getValue().contains("image")) 
				continue;
			
			return ImageIO.read( method.getResponseBodyAsStream() );
		} catch (IOException ex) {
			continue;
		}
	}
	return null;
}
 
Example 31
Project: alfresco-repository   File: DynamicSolrStoreMappingWrapperFactory.java   Source Code and License 5 votes vote down vote up
@Override
public Pair<HttpClient, String> getHttpClientAndBaseUrl()
{
   int base = ThreadLocalRandom.current().nextInt(slice.size());
   ShardInstance instance = slice.get(base);
   Pair<String, Integer> key = new Pair<String, Integer>(instance.getHostName(), instance.getPort());
   HttpClient client = clients.get(key);
   return new Pair<HttpClient, String>(client, instance.getBaseUrl());
}
 
Example 32
Project: lib-commons-httpclient   File: ChunkEncodedPost.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  if (args.length != 1)  {
      System.out.println("Usage: ChunkEncodedPost <file>");
      System.out.println("<file> - full path to a file to be posted");
      System.exit(1);
  }
  HttpClient client = new HttpClient();

  PostMethod httppost = new PostMethod("http://localhost:8080/httpclienttest/body");

  File file = new File(args[0]);

  httppost.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(file)));
  httppost.setContentChunked(true);

  try {
      client.executeMethod(httppost);

      if (httppost.getStatusCode() == HttpStatus.SC_OK) {
          System.out.println(httppost.getResponseBodyAsString());
      } else {
        System.out.println("Unexpected failure: " + httppost.getStatusLine().toString());
      }
  } finally {
      httppost.releaseConnection();
  }   
}
 
Example 33
Project: scim2-compliance-test-suite   File: CSP.java   Source Code and License 5 votes vote down vote up
public String getAccessTokenUserPass() {
    if (!StringUtils.isEmpty(this.oAuth2AccessToken)) {
        return this.oAuth2AccessToken;
    }

    if (StringUtils.isEmpty(this.username) || StringUtils.isEmpty(this.password) && StringUtils.isEmpty(this.oAuth2AuthorizationServer)
            || StringUtils.isEmpty(this.oAuth2ClientId) || StringUtils.isEmpty(this.oAuth2ClientSecret)) {
        return "";
    }

    try {
        HttpClient client = new HttpClient();
        client.getParams().setAuthenticationPreemptive(true);

        // post development
        PostMethod method = new PostMethod(this.getOAuthAuthorizationServer());
        method.setRequestHeader(new Header("Content-type", "application/x-www-form-urlencoded"));

        method.addRequestHeader("Authorization", "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes()));
        NameValuePair[] body = new NameValuePair[] { new NameValuePair("username", username), new NameValuePair("password", password),
                new NameValuePair("client_id", oAuth2ClientId), new NameValuePair("client_secret", oAuth2ClientSecret),
                new NameValuePair("grant_type", oAuth2GrantType) };
        method.setRequestBody(body);
        int responseCode = client.executeMethod(method);

        String responseBody = method.getResponseBodyAsString();
        if (responseCode != 200) {
            throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer()
                    + ", got response code " + responseCode);
        }

        JSONObject accessResponse = new JSONObject(responseBody);
        accessResponse.getString("access_token");
        return (this.oAuth2AccessToken = accessResponse.getString("access_token"));
    } catch (Exception e) {
        throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e);
    }
}
 
Example 34
Project: alfresco-repository   File: BaseWebScriptTest.java   Source Code and License 5 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();
    
    if (remoteServer != null)
    {
        httpClient = new HttpClient();
        httpClient.getParams().setBooleanParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
        if (remoteServer.username != null)
        {
            httpClient.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(remoteServer.username, remoteServer.password));
        }
    }
}
 
Example 35
Project: alfresco-repository   File: SolrStoreMappingWrapperTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testUnsharded()
{
    assertTrue(unshardedWrapper.isSharded() == false);

    Pair<HttpClient, String> distributor = unshardedWrapper.getHttpClientAndBaseUrl();
    assertNotNull(distributor);
    assertEquals("/solr4", distributor.getSecond());
    assertEquals("common", distributor.getFirst().getHostConfiguration().getHost());
    assertEquals(999, distributor.getFirst().getHostConfiguration().getPort());
}
 
Example 36
Project: automat   File: HttpUtil.java   Source Code and License 5 votes vote down vote up
public static final String httpClientPost(String url) {
	String result = "";
	HttpClient client = new HttpClient();
	GetMethod getMethod = new GetMethod(url);
	try {
		client.executeMethod(getMethod);
		result = getMethod.getResponseBodyAsString();
	} catch (Exception e) {
		logger.error(e);
	} finally {
		getMethod.releaseConnection();
	}
	return result;
}
 
Example 37
Project: Babler   File: BabelProducer.java   Source Code and License 5 votes vote down vote up
public BabelProducer(BabelBroker broker, HttpClient httpClient, String language) {
    this.broker = broker;
    this.lang = language;
    this.httpClient = httpClient;
    this.words = LanguageDataManager.getMostCommonWords(this.lang, 3000, ngram);
    this.logDb =  new LogDB(this.lang);
    this.usersLogDB = new LogDB(this.lang,"TopsyUsers");

}
 
Example 38
Project: Babler   File: BabelProducer.java   Source Code and License 5 votes vote down vote up
public BabelProducer(BabelBroker broker, HttpClient httpClient, String language, boolean user) {
    this.broker = broker;
    this.lang = language;
    this.httpClient = httpClient;
    this.logDb =  new LogDB(this.lang);
    this.usersLogDB = new LogDB(this.lang,"TopsyUsers");
    this.byUsers = user;

    if(byUsers)
        //this.users = getUserIDsFromFile();
        this.users = getUsersFromDB();
    else
        this.words = LanguageDataManager.getMostCommonWords(this.lang, 3000, ngram);

}
 
Example 39
Project: alfresco-core   File: HttpClientFactory.java   Source Code and License 5 votes vote down vote up
protected HttpClient getHttpsClient(String httpsHost, int httpsPort)
{
    // Configure a custom SSL socket factory that will enforce mutual authentication
    HttpClient httpClient = constructHttpClient();
    HttpHostFactory hostFactory = new HttpHostFactory(new Protocol("https", sslSocketFactory, httpsPort));
    httpClient.setHostConfiguration(new HostConfigurationWithHostFactory(hostFactory));
    httpClient.getHostConfiguration().setHost(httpsHost, httpsPort, "https");
    return httpClient;
}
 
Example 40
Project: jrpip   File: AuthenticatedUrl.java   Source Code and License 5 votes vote down vote up
public void setCredentialsOnClient(HttpClient client)
{
    if (this.credentials != null)
    {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, this.credentials);
    }

    if (this.cookies != null && this.cookies.length > 0)
    {
        client.getState().addCookies(this.cookies);
    }
}
 
Example 41
Project: oscm   File: ServerStatusChecker.java   Source Code and License 5 votes vote down vote up
/**
 * Basic constructor sets the listener to notify when
 * servers goes down/up. Also sets the polling time
 * which decides how long we wait between doing checks.
 * 
 * @param listener The listener
 * @param pollingTime The time we wait between checks, in milliseconds
 */
public ServerStatusChecker(ServerStatusListener listener, long pollingTime) {
    this.listener = listener;
    this.pollingTime = Math.max(30*1000, pollingTime);
    setPriority(Thread.NORM_PRIORITY-1);
    setDaemon(true);
    
    online = new LinkedList();
    offline = new LinkedList();
    httpClient = new HttpClient(); 
    httpClient.getParams().setBooleanParameter(HttpClientParams.USE_EXPECT_CONTINUE, false);
    httpClient.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
}
 
Example 42
Project: oscm   File: HttpClientFactory.java   Source Code and License 5 votes vote down vote up
public static HttpClient getHttpClient() {
    if (inTestMode) {
        try {
            Class<?> testStubClass = Class
                    .forName("org.oscm.payproc.stubs.HttpClientStub");
            return (HttpClient) testStubClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Cannot instantiate test stub");
        }
    }
    return new HttpClient();
}
 
Example 43
Project: oscm   File: PaymentServiceProviderBeanTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setup() {
    psp = new PaymentServiceProviderBean();

    HttpMethodFactory.setTestMode(true);
    PostMethodStub.reset();

    httpClientMock = mock(HttpClient.class);
    HostConfiguration hostConfigurationMock = mock(HostConfiguration.class);
    when(httpClientMock.getHostConfiguration()).thenReturn(
            hostConfigurationMock);

    psp.client = httpClientMock;

}
 
Example 44
Project: lib-commons-httpclient   File: PostXML.java   Source Code and License 5 votes vote down vote up
/**
 *
 * Usage:
 *          java PostXML http://mywebserver:80/ c:\foo.xml
 *
 *  @param args command line arguments
 *                 Argument 0 is a URL to a web server
 *                 Argument 1 is a local filename
 *
 */
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println("Usage: java -classpath <classpath> [-Dorg.apache.commons.logging.simplelog.defaultlog=<loglevel>] PostXML <url> <filename>]");
        System.out.println("<classpath> - must contain the commons-httpclient.jar and commons-logging.jar");
        System.out.println("<loglevel> - one of error, warn, info, debug, trace");
        System.out.println("<url> - the URL to post the file to");
        System.out.println("<filename> - file to post to the URL");
        System.out.println();
        System.exit(1);
    }
    // Get target URL
    String strURL = args[0];
    // Get file to be posted
    String strXMLFilename = args[1];
    File input = new File(strXMLFilename);
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    // Request content will be retrieved directly
    // from the input stream
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {
        int result = httpclient.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + result);
        // Display response
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
Example 45
Project: vind   File: RESTMetadataProvider.java   Source Code and License 5 votes vote down vote up
public RESTMetadataProvider(String baseURL,
                            String tnt,
                            String app,
                            String ws,
                            String fs,
                            String type,
                            String bearerToken) {
    this.baseURL = baseURL;
    this.bearerToken = bearerToken;
    this.path = String.format(FIELD_SET_DATA_PATH,tnt,app,ws,fs,type);
    this.client = new HttpClient();
    this.mapper = new ObjectMapper();

}
 
Example 46
Project: vind   File: RESTMetadataProvider.java   Source Code and License 5 votes vote down vote up
public RESTMetadataProvider(String baseURL,
                                 String tnt,
                                 String app,
                                 String ws,
                                 String fs,
                                 String type,
                                 String username,
                                 String password) {
    this.baseURL = baseURL;
    this.bearerToken = username+":"+password;
    this.path = String.format(FIELD_SET_DATA_PATH,tnt,app,ws,fs,type);
    this.client = new HttpClient();
    this.mapper = new ObjectMapper();
}
 
Example 47
Project: uDetective   File: ServiceNowDataSource.java   Source Code and License 5 votes vote down vote up
@Override
public Object connect() {
    HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(false);
    Credentials creds = new UsernamePasswordCredentials(AppProperties.getProperty("username"), AppProperties.getProperty("password"));
    client.getState().setCredentials(AuthScope.ANY, creds);
    
    return client;
}
 
Example 48
Project: mirrorgate-jenkins-builds-collector   File: RestCall.java   Source Code and License 5 votes vote down vote up
public MirrorGateResponse makeRestCallPost(String url, String jsonString, String user, String password) {

        MirrorGateResponse response;
        PostMethod post = new PostMethod(url);
        try {
            HttpClient client = getHttpClient();

            if (user != null && password != null) {
                client.getState().setCredentials(
                        AuthScope.ANY,
                        new UsernamePasswordCredentials(user, password));
                post.setDoAuthentication(true);
            }

            StringRequestEntity requestEntity = new StringRequestEntity(
                    jsonString,
                    "application/json",
                    "UTF-8");
            post.setRequestEntity(requestEntity);
            int responseCode = client.executeMethod(post);
            String responseString = post.getResponseBodyAsStream() != null ?
                    getResponseString(post.getResponseBodyAsStream()) : "";
            response = new MirrorGateResponse(responseCode, responseString);
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "MirrorGate: Error posting to MirrorGate", e);
            response = new MirrorGateResponse(HttpStatus.SC_BAD_REQUEST, "");
        } finally {
            post.releaseConnection();
        }
        return response;
    }
 
Example 49
Project: convertigo-engine   File: Context.java   Source Code and License 5 votes vote down vote up
public HttpClient getHttpClient3(HttpPool httpPool) {
	switch (httpPool) {
		case no:
			return HttpUtils.makeHttpClient3(false);
		case context:
			synchronized (used_connectors) {
				if (httpClient3 == null) {
					Engine.logContext.debug("Create a new context HTTP pool.");
					httpClient3 = HttpUtils.makeHttpClient3(true);
				}					
			}
			
			return httpClient3;
		case session:
			HttpClient httpClient;
			
			synchronized (used_connectors) {
				httpClient = SessionAttribute.httpClient3.get(httpSession);
				if (httpClient == null) {
					Engine.logContext.debug("Create a new session HTTP pool.");
					httpClient = HttpUtils.makeHttpClient3(true);
					SessionAttribute.httpClient3.set(httpSession, httpClient);
				}
			}
			
			return httpClient;
		case global:
			return Engine.theApp.httpClient;
	}
	return null;
}
 
Example 50
Project: lib-commons-httpclient   File: BasicAuthenticationExample.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    HttpClient client = new HttpClient();

    // pass our credentials to HttpClient, they will only be used for
    // authenticating to servers with realm "realm" on the host
    // "www.verisign.com", to authenticate against
    // an arbitrary realm or host change the appropriate argument to null.
    client.getState().setCredentials(
        new AuthScope("www.verisign.com", 443, "realm"),
        new UsernamePasswordCredentials("username", "password")
    );

    // create a GET method that reads a file over HTTPS, we're assuming
    // that this file requires basic authentication using the realm above.
    GetMethod get = new GetMethod("https://www.verisign.com/products/index.html");

    // Tell the GET method to automatically handle authentication. The
    // method will use any appropriate credentials to handle basic
    // authentication requests.  Setting this value to false will cause
    // any request for authentication to return with a status of 401.
    // It will then be up to the client to handle the authentication.
    get.setDoAuthentication( true );

    try {
        // execute the GET
        int status = client.executeMethod( get );

        // print the status and response
        System.out.println(status + "\n" + get.getResponseBodyAsString());

    } finally {
        // release any connection resources used by the method
        get.releaseConnection();
    }
}
 
Example 51
Project: kaltura-ce-sakai-extension   File: KalturaClientBase.java   Source Code and License 5 votes vote down vote up
public Element doQueue() throws KalturaApiException {
      if (this.callsQueue.isEmpty()) return null;

      if (logger.isDebugEnabled()) {
          logger.debug("service url: [" + this.kalturaConfiguration.getEndpoint() + "]");
      }

      KalturaParams kparams = new KalturaParams();
      KalturaFiles kfiles = new KalturaFiles();

      String url = extractParamsFromCallQueue(kparams, kfiles);

      logger.debug("full reqeust url: [" + url + "?" + kparams.toQueryString() + "]");

      HttpClient client = createHttpClient();
      PostMethod method = createPostMethod(kparams, kfiles, url);
String responseString = executeMethod(client, method);
      Element responseXml = XmlUtils.parseXml(responseString);
      
      this.validateXmlResult(responseXml);

      Element resultXml = null;
      try {
          resultXml = XmlUtils.getElementByXPath(responseXml, "/xml/result");
      } catch (XPathExpressionException xee) {
          throw new KalturaApiException("XPath expression exception evaluating result:" + xee);
      }

      this.throwExceptionOnAPIError(resultXml);
      
      return resultXml;
  }
 
Example 52
Project: kaltura-ce-sakai-extension   File: KalturaClientBase.java   Source Code and License 5 votes vote down vote up
private HttpClient createHttpClient() {
	HttpClient client = new HttpClient();

       // added by Unicon to handle proxy hosts
       String proxyHost = System.getProperty( "http.proxyHost" );
       if ( proxyHost != null ) {
           int proxyPort = -1;
           String proxyPortStr = System.getProperty( "http.proxyPort" );
           if (proxyPortStr != null) {
               try {
                   proxyPort = Integer.parseInt( proxyPortStr );
               } catch (NumberFormatException e) {
                   logger.warn("Invalid number for system property http.proxyPort ("+proxyPortStr+"), using default port instead");
               }
           }
           ProxyHost proxy = new ProxyHost( proxyHost, proxyPort );
           client.getHostConfiguration().setProxyHost( proxy );
       }        
       // added by Unicon to force encoding to UTF-8
       client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, UTF8_CHARSET);
       client.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, UTF8_CHARSET);
       client.getParams().setParameter(HttpMethodParams.HTTP_URI_CHARSET, UTF8_CHARSET);
       
       HttpConnectionManagerParams connParams = client.getHttpConnectionManager().getParams();
       if(this.kalturaConfiguration.getTimeout() != 0) {
       	connParams.setSoTimeout(this.kalturaConfiguration.getTimeout());
       	connParams.setConnectionTimeout(this.kalturaConfiguration.getTimeout());
       }
	client.getHttpConnectionManager().setParams(connParams);
	return client;
}
 
Example 53
Project: mirrorgate-jenkins-builds-collector   File: DefaultMirrorGateServiceTest.java   Source Code and License 5 votes vote down vote up
@Before
@Override
public void setUp() {
    PowerMockito.mockStatic(Jenkins.class);
    PowerMockito.when(Jenkins.getInstance()).thenReturn(jenkins);
    PowerMockito.when(jenkins.getDescriptorByType(any()))
            .thenReturn(descriptor);

    htppClient = mock(HttpClient.class);

    when(restCall.getHttpClient()).thenReturn(htppClient);
    when(service.buildRestCall()).thenReturn(restCall);
}
 
Example 54
Project: Equella   File: SruServiceImpl.java   Source Code and License 5 votes vote down vote up
private HttpMethod executeQuery(FederatedSearch sruSearch, String query, SRUSettings settings, int offset,
	int perpage) throws IOException
{
	HttpMethod httpMethod = null;

	try
	{
		// URL includes the port (if any) we trust ...
		URL url = new URL(settings.getUrl());
		PostMethod postMethod = new PostMethod(url.toExternalForm());
		NameValuePair[] nameValuePairs = populateNameValuePairs(query, settings, offset, perpage);
		postMethod.addParameters(nameValuePairs);
		httpMethod = postMethod;
	}
	catch( Exception e )
	{
		throw new RuntimeException(e);
	}

	HttpClient httpClient = new HttpClient();
	httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(sruSearch.getTimeout() * 1000);
	httpClient.getHttpConnectionManager().getParams().setSoTimeout(sruSearch.getTimeout() * 1000);
	// Prevent the default 3 tries - so once is enough ...?
	httpClient.getHttpConnectionManager().getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
		new DefaultHttpMethodRetryHandler(0, false));

	httpClient.executeMethod(httpMethod);

	return httpMethod;
}
 
Example 55
Project: lams   File: HttpClientBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * Builds an HTTP client with the given settings. Settings are NOT reset to their default values after a client has
 * been created.
 * 
 * @return the created client.
 */
public HttpClient buildClient() {
    if (httpsProtocolSocketFactory != null) {
        Protocol.registerProtocol("https", new Protocol("https", httpsProtocolSocketFactory, 443));
    }

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setAuthenticationPreemptive(isPreemptiveAuthentication());
    clientParams.setContentCharset(getContentCharSet());
    clientParams.setParameter(HttpClientParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(
            connectionRetryAttempts, false));

    HttpConnectionManagerParams connMgrParams = new HttpConnectionManagerParams();
    connMgrParams.setConnectionTimeout(getConnectionTimeout());
    connMgrParams.setDefaultMaxConnectionsPerHost(getMaxConnectionsPerHost());
    connMgrParams.setMaxTotalConnections(getMaxTotalConnections());
    connMgrParams.setReceiveBufferSize(getReceiveBufferSize());
    connMgrParams.setSendBufferSize(getSendBufferSize());
    connMgrParams.setTcpNoDelay(isTcpNoDelay());

    MultiThreadedHttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager();
    connMgr.setParams(connMgrParams);

    HttpClient httpClient = new HttpClient(clientParams, connMgr);

    if (proxyHost != null) {
        HostConfiguration hostConfig = new HostConfiguration();
        hostConfig.setProxy(proxyHost, proxyPort);
        httpClient.setHostConfiguration(hostConfig);

        if (proxyUsername != null) {
            AuthScope proxyAuthScope = new AuthScope(proxyHost, proxyPort);
            UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(proxyUsername,
                    proxyPassword);
            httpClient.getState().setProxyCredentials(proxyAuthScope, proxyCredentials);
        }
    }

    return httpClient;
}
 
Example 56
Project: lams   File: HttpSOAPClient.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param client Client used to make outbound HTTP requests. This client SHOULD employ a
 *            {@link org.apache.commons.httpclient.MultiThreadedHttpConnectionManager} and may be shared with other
 *            objects.
 * @param parser pool of XML parsers used to parse incoming responses
 */
public HttpSOAPClient(HttpClient client, ParserPool parser) {
    if (client == null) {
        throw new IllegalArgumentException("HtppClient may not be null");
    }
    httpClient = client;

    if (parser == null) {
        throw new IllegalArgumentException("ParserPool may not be null");
    }
    parserPool = parser;
}
 
Example 57
Project: lams   File: HttpResource.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param resource HTTP(S) URL of the resource
 */
public HttpResource(String resource) {
    super();

    resourceUrl = DatatypeHelper.safeTrimOrNullString(resource);
    if (resourceUrl == null) {
        throw new IllegalArgumentException("Resource URL may not be null or empty");
    }

    httpClient = new HttpClient();
}
 
Example 58
Project: lams   File: HttpResource.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param resource HTTP(S) URL of the resource
 * @param resourceFilter filter to apply to this resource
 * 
 * @deprecated use {@link #setResourceFilter(ResourceFilter)} instead
 */
public HttpResource(String resource, ResourceFilter resourceFilter) {
    super(resourceFilter);

    resourceUrl = DatatypeHelper.safeTrimOrNullString(resource);
    if (resourceUrl == null) {
        throw new IllegalArgumentException("Resource URL may not be null or empty");
    }

    httpClient = new HttpClient();
}
 
Example 59
Project: iBase4J   File: HttpUtil.java   Source Code and License 5 votes vote down vote up
public static final String httpClientPost(String url) {
	String result = "";
	HttpClient client = new HttpClient();
	GetMethod getMethod = new GetMethod(url);
	try {
		client.executeMethod(getMethod);
		result = getMethod.getResponseBodyAsString();
	} catch (Exception e) {
		logger.error(e);
	} finally {
		getMethod.releaseConnection();
	}
	return result;
}
 
Example 60
Project: bibliometrics   File: MyCoReConnector.java   Source Code and License 5 votes vote down vote up
private MCRContent getResponse(String queryURL) throws IOException {
    //prepare http client
    HttpClient client = new HttpClient();

    //prepare GET-request
    connection = new GetMethod(queryURL);

    //execute request, get response from API and return as stream
    client.executeMethod(connection);
    InputStream response = connection.getResponseBodyAsStream();
    return new MCRStreamContent(response);
}