本文整理匯總了Java中org.apache.commons.httpclient.HttpState類的典型用法代碼示例。如果您正苦於以下問題:Java HttpState類的具體用法?Java HttpState怎麽用?Java HttpState使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
HttpState類屬於org.apache.commons.httpclient包,在下文中一共展示了HttpState類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: addRequestHeaders
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
/**
* Sets the <tt>Expect</tt> header if it has not already been set,
* in addition to the "standard" set of headers.
*
* @param state the {@link HttpState state} information associated with this method
* @param conn the {@link HttpConnection connection} used to execute
* this HTTP method
*
* @throws IOException if an I/O (transport) error occurs. Some transport exceptions
* can be recovered from.
* @throws HttpException if a protocol exception occurs. Usually protocol exceptions
* cannot be recovered from.
*/
protected void addRequestHeaders(HttpState state, HttpConnection conn)
throws IOException, HttpException {
LOG.trace("enter ExpectContinueMethod.addRequestHeaders(HttpState, HttpConnection)");
super.addRequestHeaders(state, conn);
// If the request is being retried, the header may already be present
boolean headerPresent = (getRequestHeader("Expect") != null);
// See if the expect header should be sent
// = HTTP/1.1 or higher
// = request body present
if (getParams().isParameterTrue(HttpMethodParams.USE_EXPECT_CONTINUE)
&& getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1)
&& hasRequestContent())
{
if (!headerPresent) {
setRequestHeader("Expect", "100-continue");
}
} else {
if (headerPresent) {
removeRequestHeader("Expect");
}
}
}
示例2: testSuccessfulVerifyTargetOverHttps
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
public void testSuccessfulVerifyTargetOverHttps() throws Exception
{
//Stub HttpClient so that executeMethod returns a 200 response
when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class),
any(HttpState.class))).thenReturn(200);
target.setEndpointProtocol(HTTPS_PROTOCOL);
target.setEndpointPort(HTTPS_PORT);
//Call verifyTarget
transmitter.verifyTarget(target);
ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class);
ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class);
ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class);
verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture());
assertEquals("port", HTTPS_PORT, hostConfig.getValue().getPort());
assertTrue("socket factory",
hostConfig.getValue().getProtocol().getSocketFactory() instanceof SecureProtocolSocketFactory);
assertEquals("protocol", HTTPS_PROTOCOL.toLowerCase(),
hostConfig.getValue().getProtocol().getScheme().toLowerCase());
}
示例3: writeRequest
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
@Override
protected void writeRequest(HttpState state, HttpConnection conn) throws IOException
{
try
{
BufferedChunkedOutputStream bufferedChunkedOutputStream = new BufferedChunkedOutputStream(conn, state, this);
this.writer.write(bufferedChunkedOutputStream);
bufferedChunkedOutputStream.finish();
conn.flushRequestOutputStream();
}
catch (IOException e)
{
this.cleanupConnection(conn);
throw e;
}
}
示例4: writeRequest
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
@Override
protected void writeRequest(HttpState state, HttpConnection conn) throws IOException
{
try
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(2048);
this.writer.write(outputStream);
outputStream.close();
this.result = outputStream.toByteArray();
this.setRequestEntity(this);
this.writeRequestLine(state, conn);
this.writeRequestHeaders(state, conn);
conn.writeLine(); // close head
// make sure the status line and headers have been sent
conn.flushRequestOutputStream();
this.writeRequestBody(state, conn);
conn.flushRequestOutputStream();
}
catch (IOException e)
{
this.cleanupConnection(conn);
throw e;
}
}
示例5: getHttpState
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
private synchronized void getHttpState(Shuttle shuttle) {
if (authenticationPropertiesHasChanged) {
context.httpState = null;
authenticationPropertiesHasChanged = false;
}
if (context.httpState == null) {
Engine.logSiteClipper.debug("(SiteClipperConnector) Creating new HttpState for context id " + context.contextID);
context.httpState = new HttpState();
} else {
Engine.logSiteClipper.debug("(SiteClipperConnector) Using HttpState of context id " + context.contextID);
}
if (!authUser.equals("") || !authPassword.equals("") || (givenAuthUser != null) || (givenAuthPassword != null)) {
int indexSlash = (givenAuthUser == null) ? -1 : givenAuthUser.indexOf("\\");
String domain = (indexSlash == -1) ? NTLMAuthenticationDomain : givenAuthUser.substring(0, indexSlash);
String user = (givenAuthUser == null) ? authUser : givenAuthUser.substring(indexSlash + 1);
String password = (givenAuthPassword == null) ? authPassword : givenAuthPassword;
String type = (givenAuthMode == null ? authenticationType.name() : givenAuthMode);
String host = hostConfiguration != null ? hostConfiguration.getHost() : shuttle.getRequest(QueryPart.host);
AuthenticationMode.get(type).setCredentials(context.httpState, user, password, host, domain);
}
}
示例6: addContentTypeRequestHeader
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
/**
* Adds a <tt>Content-Type</tt> request header.
*
* @param state current state of http requests
* @param conn the connection to use for I/O
*
* @throws IOException if an I/O (transport) error occurs. Some transport exceptions
* can be recovered from.
* @throws HttpException if a protocol exception occurs. Usually protocol exceptions
* cannot be recovered from.
*
* @since 3.0
*/
protected void addContentTypeRequestHeader(HttpState state,
HttpConnection conn)
throws IOException, HttpException {
LOG.trace("enter EntityEnclosingMethod.addContentTypeRequestHeader("
+ "HttpState, HttpConnection)");
if (!parameters.isEmpty()) {
StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
if (Part.getBoundary() != null) {
buffer.append("; boundary=");
buffer.append(Part.getBoundary());
}
setRequestHeader("Content-Type", buffer.toString());
}
}
示例7: processResponseHeaders
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
/**
* <p>
* This implementation will parse the <tt>Allow</tt> header to obtain
* the set of methods supported by the resource identified by the Request-URI.
* </p>
*
* @param state the {@link HttpState state} information associated with this method
* @param conn the {@link HttpConnection connection} used to execute
* this HTTP method
*
* @see #readResponse
* @see #readResponseHeaders
* @since 2.0
*/
protected void processResponseHeaders(HttpState state, HttpConnection conn) {
LOG.trace("enter OptionsMethod.processResponseHeaders(HttpState, HttpConnection)");
Header allowHeader = getResponseHeader("allow");
if (allowHeader != null) {
String allowHeaderValue = allowHeader.getValue();
StringTokenizer tokenizer =
new StringTokenizer(allowHeaderValue, ",");
while (tokenizer.hasMoreElements()) {
String methodAllowed =
tokenizer.nextToken().trim().toUpperCase();
methodsAllowed.addElement(methodAllowed);
}
}
}
示例8: addContentLengthRequestHeader
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
/**
* Generates <tt>Content-Length</tt> or <tt>Transfer-Encoding: Chunked</tt>
* request header, as long as no <tt>Content-Length</tt> request header
* already exists.
*
* @param state current state of http requests
* @param conn the connection to use for I/O
*
* @throws IOException when errors occur reading or writing to/from the
* connection
* @throws HttpException when a recoverable error occurs
*/
protected void addContentLengthRequestHeader(HttpState state,
HttpConnection conn)
throws IOException, HttpException {
LOG.trace("enter EntityEnclosingMethod.addContentLengthRequestHeader("
+ "HttpState, HttpConnection)");
if ((getRequestHeader("content-length") == null)
&& (getRequestHeader("Transfer-Encoding") == null)) {
long len = getRequestContentLength();
if (len < 0) {
if (getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1)) {
addRequestHeader("Transfer-Encoding", "chunked");
} else {
throw new ProtocolException(getEffectiveVersion() +
" does not support chunk encoding");
}
} else {
addRequestHeader("Content-Length", String.valueOf(len));
}
}
}
示例9: testParseMultipleDifferentPaths
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
public void testParseMultipleDifferentPaths() throws Exception {
Header header = new Header("Set-Cookie",
"name1=value1;Version=1;Path=/commons,name1=value2;Version=1;" +
"Path=/commons/httpclient;Version=1");
CookieSpec cookiespec = new CookieSpecBase();
Cookie[] parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/httpclient", true, header);
HttpState state = new HttpState();
state.addCookies(parsed);
Cookie[] cookies = state.getCookies();
assertEquals("Wrong number of cookies.",2,cookies.length);
assertEquals("Name","name1",cookies[0].getName());
assertEquals("Value","value1",cookies[0].getValue());
assertEquals("Name","name1",cookies[1].getName());
assertEquals("Value","value2",cookies[1].getValue());
}
示例10: testPreemptiveAuthorization
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
/**
* Make sure preemptive authorization works when the server requires NLM.
* @throws Exception
*/
public void testPreemptiveAuthorization() throws Exception {
NTCredentials creds =
new NTCredentials("testuser", "testpass", "host", "domain");
HttpState state = new HttpState();
state.setCredentials(AuthScope.ANY, creds);
this.client.setState(state);
this.client.getParams().setAuthenticationPreemptive(true);
this.server.setHttpService(new PreemptiveNTLMAuthService());
GetMethod httpget = new GetMethod("/test/");
try {
this.client.executeMethod(httpget);
} finally {
httpget.releaseConnection();
}
assertNotNull(httpget.getStatusLine());
assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
}
示例11: getClient
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
private void getClient(){
CONTACT_URL = OscarProperties.getInstance().getProperty("TELEPLAN_URL",CONTACT_URL);
HttpState initialState = new HttpState();
// Initial set of cookies can be retrieved from persistent storage and
// re-created, using a persistence mechanism of choice,
Cookie mycookie = new Cookie("moh.hnet.bc.ca","mycookie", "stuff", "/", null, false); // and then added to your HTTP state instance
initialState.addCookie(mycookie);
// Get HTTP client instance
//HttpClientParams hcParams = new HttpClientParams();
//hcParams.setParameter("User-Agent","TeleplanPerl 1.0");
httpclient = new HttpClient(); //hcParams);
httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
httpclient.setState(initialState);
httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
httpclient.getParams().setParameter("User-Agent","TeleplanPerl 1.0");
}
示例12: executeMethod
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
public int executeMethod(HostConfiguration hostconfig, HttpMethod method, HttpState state, boolean addCasTicket)
throws IOException, HttpException {
if (LOG.isDebugEnabled()) {
LOG.debug("executeMethod(HostConfiguration, HttpMethod, HttpState) - entering");
}
try {
if (this.isAddCasTicketParams()) {
HttpClientCAS.addCASTicket(method);
}
} catch (MotuCasException e) {
throw new HttpException(e.notifyException(), e);
}
int returnint = super.executeMethod(hostconfig, method, state);
if (LOG.isDebugEnabled()) {
LOG.debug("executeMethod(HostConfiguration, HttpMethod, HttpState) - exiting");
}
return returnint;
}
示例13: setConnectionAuthorization
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
/**
* Extracts all the required authorization for that particular URL request
* and sets it in the <code>HttpMethod</code> passed in.
*
* @param client the HttpClient object
*
* @param u
* <code>URL</code> of the URL request
* @param authManager
* the <code>AuthManager</code> containing all the authorisations for
* this <code>UrlConfig</code>
*/
private void setConnectionAuthorization(HttpClient client, URL u, AuthManager authManager) {
HttpState state = client.getState();
if (authManager != null) {
HttpClientParams params = client.getParams();
Authorization auth = authManager.getAuthForURL(u);
if (auth != null) {
String username = auth.getUser();
String realm = auth.getRealm();
String domain = auth.getDomain();
if (log.isDebugEnabled()){
log.debug(username + " > D="+ username + " D="+domain+" R="+realm);
}
state.setCredentials(
new AuthScope(u.getHost(),u.getPort(),
realm.length()==0 ? null : realm //"" is not the same as no realm
,AuthScope.ANY_SCHEME),
// NT Includes other types of Credentials
new NTCredentials(
username,
auth.getPass(),
localHost,
domain
));
// We have credentials - should we set pre-emptive authentication?
if (canSetPreEmptive){
log.debug("Setting Pre-emptive authentication");
params.setAuthenticationPreemptive(true);
}
} else {
state.clearCredentials();
if (canSetPreEmptive){
params.setAuthenticationPreemptive(false);
}
}
} else {
state.clearCredentials();
}
}
示例14: processResponseBody
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
/**
* Overridden to process the sync-token. Adapted from DavMethodBase.
*
* @see DavMethodBase#processResponseBody(HttpState, HttpConnection)
*/
@Override
protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) {
if (getStatusCode() == DavServletResponse.SC_MULTI_STATUS) {
try {
Document document = getResponseBodyAsDocument();
if (document != null) {
synctoken = DomUtil.getChildText(document.getDocumentElement(), SyncReportInfo.XML_SYNC_TOKEN, DavConstants.NAMESPACE);
log.info("Sync-Token for REPORT: " + synctoken);
multiStatus = MultiStatus.createFromXml(document.getDocumentElement());
processMultiStatusBody(multiStatus, httpState, httpConnection);
}
} catch (IOException e) {
log.error("Error while parsing sync-token.", e);
setSuccess(false);
}
}
}
示例15: _invoke
import org.apache.commons.httpclient.HttpState; //導入依賴的package包/類
private static HTTPResponse _invoke(HttpMethod httpMethod, URL url, String username, String password, long timeout, int maxRedirect,
String charset, String useragent, ProxyData proxy, Header[] headers, Map<String,String> params, Object body) throws IOException {
HttpClient client = new HttpClient();
HostConfiguration config = client.getHostConfiguration();
HttpState state = client.getState();
setHeader(httpMethod,headers);
if(CollectionUtil.isEmpty(params))setContentType(httpMethod,charset);
setUserAgent(httpMethod,useragent);
setTimeout(client,timeout);
setParams(httpMethod,params);
setCredentials(client,httpMethod,username,password);
setProxy(config,state,proxy);
if(body!=null && httpMethod instanceof EntityEnclosingMethod)setBody((EntityEnclosingMethod)httpMethod,body);
return new HTTPResponse3Impl(execute(client,httpMethod,maxRedirect),url);
}