本文整理匯總了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();
}
}
示例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();
}
}
示例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("==================");
}
示例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;
}
示例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);
}
示例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;
}
示例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);
}
示例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;
}
示例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 ();
}
}
示例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;
}
示例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;
}
示例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();
}
}
}
示例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;
}
示例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();
}
}
}
示例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");
}