当前位置: 首页>>代码示例>>Java>>正文


Java HttpClient类代码示例

本文整理汇总了Java中org.apache.commons.httpclient.HttpClient的典型用法代码示例。如果您正苦于以下问题:Java HttpClient类的具体用法?Java HttpClient怎么用?Java HttpClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpClient类属于org.apache.commons.httpclient包,在下文中一共展示了HttpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: get

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
@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();
  }
}
 
开发者ID:logistimo,项目名称:logistimo-web-service,代码行数:22,代码来源:LogiURLFetchService.java

示例2: post

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
@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();
  }

}
 
开发者ID:logistimo,项目名称:logistimo-web-service,代码行数:25,代码来源:LogiURLFetchService.java

示例3: chcekConnectionStatus

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
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("==================");
    }
 
开发者ID:capitalone,项目名称:Hydrograph,代码行数:23,代码来源:HydrographServiceClient.java

示例4: getPostResponseHeader

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
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;
  }
 
开发者ID:noseparte,项目名称:Spring-Boot-Server,代码行数:27,代码来源:HttpUtils.java

示例5: HttpClientTransmitterImpl

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
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);
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:22,代码来源:HttpClientTransmitterImpl.java

示例6: postSolrQuery

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
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;
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:27,代码来源:SolrQueryHTTPClient.java

示例7: getHttpClientAndBaseUrl

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
/**
 * @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);
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:20,代码来源:ExplicitSolrStoreMappingWrapper.java

示例8: httpClientPost

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
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;
}
 
开发者ID:guokezheng,项目名称:automat,代码行数:20,代码来源:HttpUtil.java

示例9: getData

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
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 ();
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:20,代码来源:HdHttpClient.java

示例10: constructHttpClient

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
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;
}
 
开发者ID:Alfresco,项目名称:alfresco-core,代码行数:19,代码来源:HttpClientFactory.java

示例11: getHttpClient

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
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;
}
 
开发者ID:Alfresco,项目名称:alfresco-core,代码行数:20,代码来源:HttpClientFactory.java

示例12: fastFailPing

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
/**
 * @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();
        }
    }
}
 
开发者ID:goldmansachs,项目名称:jrpip,代码行数:24,代码来源:FastServletProxyFactory.java

示例13: getHttpClient

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
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;
}
 
开发者ID:goldmansachs,项目名称:jrpip,代码行数:9,代码来源:FastServletProxyFactory.java

示例14: requestNewSession

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
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();
        }
    }
}
 
开发者ID:goldmansachs,项目名称:jrpip,代码行数:25,代码来源:FastServletProxyFactory.java

示例15: downloadPacContent

import org.apache.commons.httpclient.HttpClient; //导入依赖的package包/类
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");
}
 
开发者ID:convertigo,项目名称:convertigo-engine,代码行数:18,代码来源:PacManager.java


注:本文中的org.apache.commons.httpclient.HttpClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。