下面列出了怎么用org.apache.commons.httpclient.HttpState的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @inheritDoc
*/
@Override
public void updateMessage(ExchangeSession.Message message, Map<String, String> properties) throws IOException {
PropPatchMethod patchMethod = new PropPatchMethod(encodeAndFixUrl(message.permanentUrl), buildProperties(properties)) {
@Override
protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) {
// ignore response body, sometimes invalid with exchange mapi properties
}
};
try {
int statusCode = httpClient.executeMethod(patchMethod);
if (statusCode != HttpStatus.SC_MULTI_STATUS) {
throw new DavMailException("EXCEPTION_UNABLE_TO_UPDATE_MESSAGE");
}
} finally {
patchMethod.releaseConnection();
}
}
/**
* Test create target.
*
* @throws Exception
*/
public void testSuccessfulVerifyTargetOverHttp() 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);
//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());
assertTrue("post method", httpMethod.getValue() instanceof PostMethod);
assertEquals("host name", TARGET_HOST, hostConfig.getValue().getHost());
assertEquals("port", HTTP_PORT, hostConfig.getValue().getPort());
assertEquals("protocol", HTTP_PROTOCOL.toLowerCase(),
hostConfig.getValue().getProtocol().getScheme().toLowerCase());
assertEquals("path", TRANSFER_SERVICE_PATH + "/test", httpMethod.getValue().getPath());
}
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());
}
@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;
}
}
@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;
}
}
public HttpClient getHttpClient() {
String proxyUrl = System.getProperty("http.proxyHost");
String proxyPort = System.getProperty("http.proxyPort");
String proxyUser = System.getProperty("http.proxyUsername");
String proxyPassword = System.getProperty("http.proxyPassword");
HttpClient client = new HttpClient();
if (proxyUrl != null && proxyPort != null) {
logger.debug("Setting proxy configuration ...");
client.getHostConfiguration().setProxy(proxyUrl, Integer.parseInt(proxyPort));
if (proxyUser != null) {
logger.debug("Setting proxy authentication configuration ...");
HttpState state = new HttpState();
state.setProxyCredentials(null, null, new UsernamePasswordCredentials(proxyUser, proxyPassword));
client.setState(state);
}
} else {
logger.debug("No proxy configuration found");
}
return client;
}
/**
* 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());
}
}
/**
* <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);
}
}
}
/**
* 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));
}
}
}
/**
* 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");
}
}
}
private void createHttpClient() {
Protocol protocol = Protocol.getProtocol("https");
if (protocol == null) {
// ZAP: Dont override an existing protocol - it causes problems with ZAP
Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", easyhttps);
}
initialState = new HttpState();
MultiThreadedHttpConnectionManager connectionManager =
new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(1000);
connectionManager.getParams().setMaxTotalConnections(1000);
// connectionManager.set
httpclient = new HttpClient(connectionManager);
// httpclient.
}
@Override
protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) {
Header contentTypeHeader = getResponseHeader("Content-Type");
if (contentTypeHeader != null && "text/xml; charset=utf-8".equals(contentTypeHeader.getValue())) {
try {
if (DavGatewayHttpClientFacade.isGzipEncoded(this)) {
processResponseStream(new GZIPInputStream(getResponseBodyAsStream()));
} else {
processResponseStream(getResponseBodyAsStream());
}
} catch (IOException e) {
LOGGER.error("Error while parsing soap response: " + e, e);
}
}
}
@Override
protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) {
Header contentTypeHeader = getResponseHeader("Content-Type");
if (contentTypeHeader != null && "text/xml".equals(contentTypeHeader.getValue())) {
responses = new ArrayList<>();
XMLStreamReader reader;
try {
reader = XMLStreamUtil.createXMLStreamReader(new FilterInputStream(getResponseBodyAsStream()) {
final byte[] lastbytes = new byte[3];
@Override
public int read(byte[] bytes, int off, int len) throws IOException {
int count = in.read(bytes, off, len);
// patch invalid element name
for (int i = 0; i < count; i++) {
byte currentByte = bytes[off + i];
if ((lastbytes[0] == '<') && (currentByte >= '0' && currentByte <= '9')) {
// move invalid first tag char to valid range
bytes[off + i] = (byte) (currentByte + 49);
}
lastbytes[0] = lastbytes[1];
lastbytes[1] = lastbytes[2];
lastbytes[2] = currentByte;
}
return count;
}
});
while (reader.hasNext()) {
reader.next();
if (XMLStreamUtil.isStartTag(reader, "response")) {
handleResponse(reader);
}
}
} catch (IOException | XMLStreamException e) {
LOGGER.error("Error while parsing soap response: " + e, e);
}
}
}
@Override
protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) {
Header contentTypeHeader = getResponseHeader("Content-Type");
if (contentTypeHeader != null && "application/json; charset=utf-8".equals(contentTypeHeader.getValue())) {
try {
if (DavGatewayHttpClientFacade.isGzipEncoded(this)) {
processResponseStream(new GZIPInputStream(getResponseBodyAsStream()));
} else {
processResponseStream(getResponseBodyAsStream());
}
} catch (IOException | JSONException e) {
LOGGER.error("Error while parsing json response: " + e, e);
}
}
}
/**
* <p>
* 初始化HttpClient对象,同时设置转发应用的Cookie信息。
* 将当前请求中的cookie信息(除去sessionId cookie 和 token cookie)设置到新的请求中来
* </p>
* @param targetAS 转发的目标应用
* @return
*/
public static HttpClient getHttpClient(AppServer targetAS) {
HttpState initialState = new HttpState();
HttpServletRequest request = Context.getRequestContext().getRequest();
javax.servlet.http.Cookie[] cookies = request.getCookies();
cookies = (javax.servlet.http.Cookie[]) EasyUtils.checkNull(cookies, new javax.servlet.http.Cookie[] {});
// 设置转发Cookies信息
AppServer currentAS = Context.getApplicationContext().getCurrentAppServer();
for (javax.servlet.http.Cookie cookie : request.getCookies()) {
String cookieName = cookie.getName();
if (cookieName.equals(currentAS.getSessionIdName())
|| cookieName.equals(RequestContext.USER_TOKEN)) {
continue;
}
// 保存当前应用以外的sessionId信息的cookie一般是以其应用Code命名的,当前应用的则以JSESSIONID命名
if (cookieName.equals(targetAS.getCode())) {
cookieName = targetAS.getSessionIdName();
}
String domain = targetAS.getDomain();
String path = targetAS.getPath();
Cookie apacheCookie = new Cookie(domain, cookieName, cookie.getValue(), path, null, request.isSecure());
initialState.addCookie(apacheCookie);
}
HttpClient client = getHttpClient();
client.setState(initialState);
return client;
}
/**
* <p>
* 请求转向不同同服务器的其他应用
* </p>
* @param appServer
* @param req
* @param response
* @throws IOException
* @throws BusinessServletException
*/
private void proxy4ForeignApplication(AppServer appServer, HttpServletResponse response) throws IOException, BusinessServletException {
HttpClient client = HttpClientUtil.getHttpClient(appServer); // 创建HttpClient对象
HttpState httpState = client.getState();
/* 设置用户令牌相关Cookie,包括一个token Cookie和一个 sessionId Cookie */
boolean isSecure = Context.getRequestContext().isSecure(); //是否https请求
String currentAppCode = Context.getApplicationContext().getCurrentAppCode(); //当前应用code
String domain = appServer.getDomain();
String path = appServer.getPath();
if (Context.isOnline()) {
httpState.addCookie(new Cookie(domain, RequestContext.USER_TOKEN, Context.getToken(), path, null, isSecure)); //token = ****************
}
if (Environment.getSessionId() != null) {
httpState.addCookie(new Cookie(domain, currentAppCode, Environment.getSessionId(), path, null, isSecure)); // TSS = JSessionId
}
HttpMethod httpMethod = HttpClientUtil.getHttpMethod(appServer); // 创建HttpPost对象(等价于一个Post Http Request)
try {
// 请求
int statusCode = client.executeMethod(httpMethod);
if (statusCode == HttpStatus.SC_OK) {
// 转发返回信息
transmitResponse(appServer, response, client, httpMethod);
}
else if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
|| (statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
|| (statusCode == HttpStatus.SC_SEE_OTHER)
|| (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
dealWithRedirect(appServer, response, client, httpMethod);
}
} finally {
httpMethod.releaseConnection();
}
}
public void testHttpsVerifyTargetWithCustomSocketFactory() throws Exception
{
//Override the default SSL socket factory with our own custom one...
CustomSocketFactory socketFactory = new CustomSocketFactory();
transmitter.setHttpsSocketFactory(socketFactory);
target.setEndpointProtocol(HTTPS_PROTOCOL);
target.setEndpointPort(HTTPS_PORT);
//Stub HttpClient so that executeMethod returns a 200 response
when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class),
any(HttpState.class))).thenReturn(200);
//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());
//test that the socket factory passed to HttpClient is our custom one (intentional use of '==')
assertTrue("socket factory", hostConfig.getValue().getProtocol().getSocketFactory() == socketFactory);
assertEquals("protocol", HTTPS_PROTOCOL.toLowerCase(),
hostConfig.getValue().getProtocol().getScheme().toLowerCase());
}
public void testUnauthorisedVerifyTarget() throws Exception
{
//Stub HttpClient so that executeMethod returns a 401 response
when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class),
any(HttpState.class))).thenReturn(401);
try
{
transmitter.verifyTarget(target);
}
catch (TransferException ex)
{
//expected
}
}
public void testGetStatusErrorRehydration() throws Exception
{
final ExceptionJsonSerializer errorSerializer = new ExceptionJsonSerializer();
final TransferException expectedException = new TransferException("my message id", new Object[] {"param1", "param2"});
when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class),
any(HttpState.class))).thenReturn(200);
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable
{
JSONObject progressObject = new JSONObject();
progressObject.put("transferId", "mytransferid");
progressObject.put("status", Status.ERROR);
progressObject.put("currentPosition", 1);
progressObject.put("endPosition", 10);
JSONObject errorObject = errorSerializer.serialize(expectedException);
progressObject.put("error", errorObject);
return progressObject.toString();
}
}).when(mockedHttpMethodFactory.latestPostMethod).getResponseBodyAsString();
Transfer transfer = new Transfer();
transfer.setTransferId("mytransferid");
transfer.setTransferTarget(target);
TransferProgress progress = transmitter.getStatus(transfer);
assertTrue(progress.getError() != null);
assertEquals(expectedException.getClass(), progress.getError().getClass());
TransferException receivedException = (TransferException)progress.getError();
assertEquals(expectedException.getMsgId(), receivedException.getMsgId());
assertTrue(Arrays.deepEquals(expectedException.getMsgParams(), receivedException.getMsgParams()));
}
public void testBeginFailure() throws Exception
{
final ExceptionJsonSerializer errorSerializer = new ExceptionJsonSerializer();
final TransferException expectedException = new TransferException("my message id", new Object[] {"param1", "param2"});
when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class),
any(HttpState.class))).thenReturn(500);
doAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable
{
JSONObject errorObject = errorSerializer.serialize(expectedException);
return errorObject.toString();
}
}).when(mockedHttpMethodFactory.latestPostMethod).getResponseBodyAsString();
try
{
transmitter.begin(target, "1234", new TransferVersionImpl("2", "2", "2", "Dummy"));
fail();
}
catch(TransferException ex)
{
assertEquals(expectedException.getClass(), ex.getClass());
assertEquals(expectedException.getMsgId(), ex.getMsgId());
assertTrue(Arrays.deepEquals(expectedException.getMsgParams(), ex.getMsgParams()));
}
}
public void reallyWriteHeaders(HttpState state, HttpConnection conn) throws IOException
{
this.writeRequestLine(state, conn);
this.writeRequestHeaders(state, conn);
conn.writeLine(); // close head
// make sure the status line and headers have been sent
conn.flushRequestOutputStream();
}
public BufferedChunkedOutputStream(
HttpConnection conn,
HttpState state,
StreamedPostMethod streamedPostMethod) throws IOException
{
this.streamedPostMethod = streamedPostMethod;
this.state = state;
this.httpConnection = conn;
this.cache = new byte[2048];
this.stream = this.httpConnection.getRequestOutputStream();
}
public HttpClient createHttpClient() {
HttpClient client = new HttpClient();
String proxyHost = System.getProperty(HTTPS_PROXY_HOST);
String proxyPort = System.getProperty(HTTPS_PROXY_PORT);
String proxyUser = System.getProperty(HTTPS_PROXY_USER);
String proxyPassword = System.getProperty(HTTPS_PROXY_PASSWORD);
int proxyPortInt = 0;
try {
proxyPortInt = Integer.parseInt(proxyPort);
} catch (NumberFormatException e) {
// ignore
}
if (!useProxyByPass(this.apiUrl)) {
if (proxyHost != null && proxyPortInt > 0) {
client.getHostConfiguration().setProxy(proxyHost, proxyPortInt);
if (proxyUser != null && proxyUser.length() > 0
&& proxyPassword != null && proxyPassword.length() > 0) {
HttpState state = new HttpState();
Credentials proxyCredentials = new UsernamePasswordCredentials(
proxyUser, proxyPassword);
state.setProxyCredentials(new AuthScope(proxyHost,
proxyPortInt), proxyCredentials);
client.setState(state);
}
}
}
return client;
}
/**
* Overrides {@link HttpMethodBase} method to <i>not</i> read a response
* body, despite the presence of a <tt>Content-Length</tt> or
* <tt>Transfer-Encoding</tt> header.
*
* @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.
*
* @see #readResponse
* @see #processResponseBody
*
* @since 2.0
*/
protected void readResponseBody(HttpState state, HttpConnection conn)
throws HttpException, IOException {
LOG.trace(
"enter HeadMethod.readResponseBody(HttpState, HttpConnection)");
int bodyCheckTimeout =
getParams().getIntParameter(HttpMethodParams.HEAD_BODY_CHECK_TIMEOUT, -1);
if (bodyCheckTimeout < 0) {
responseBodyConsumed();
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Check for non-compliant response body. Timeout in "
+ bodyCheckTimeout + " ms");
}
boolean responseAvailable = false;
try {
responseAvailable = conn.isResponseAvailable(bodyCheckTimeout);
} catch (IOException e) {
LOG.debug("An IOException occurred while testing if a response was available,"
+ " we will assume one is not.",
e);
responseAvailable = false;
}
if (responseAvailable) {
if (getParams().isParameterTrue(HttpMethodParams.REJECT_HEAD_BODY)) {
throw new ProtocolException(
"Body content may not be sent in response to HTTP HEAD request");
} else {
LOG.warn("Body content returned in response to HTTP HEAD");
}
super.readResponseBody(state, conn);
}
}
}
private static boolean doAuthenticateDefault(
HttpMethod method,
HttpConnection conn,
HttpState state,
boolean proxy)
throws AuthenticationException {
if (method == null) {
throw new IllegalArgumentException("HTTP method may not be null");
}
if (state == null) {
throw new IllegalArgumentException("HTTP state may not be null");
}
String host = null;
if (conn != null) {
host = proxy ? conn.getProxyHost() : conn.getHost();
}
Credentials credentials = proxy
? state.getProxyCredentials(null, host) : state.getCredentials(null, host);
if (credentials == null) {
return false;
}
if (!(credentials instanceof UsernamePasswordCredentials)) {
throw new InvalidCredentialsException(
"Credentials cannot be used for basic authentication: "
+ credentials.toString());
}
String auth = BasicScheme.authenticate(
(UsernamePasswordCredentials) credentials,
method.getParams().getCredentialCharset());
if (auth != null) {
String s = proxy ? PROXY_AUTH_RESP : WWW_AUTH_RESP;
Header header = new Header(s, auth, true);
method.addRequestHeader(header);
return true;
} else {
return false;
}
}
/**
* This is meant for system use so you should not be constructing this,
* use the {@link HttpRESTUtils#makeReusableHttpClient(boolean, int, javax.servlet.http.Cookie[])} instead
*/
public HttpClientWrapper(HttpClient httpClient,
MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager,
HttpState initialHttpState) {
super();
this.httpClient = httpClient;
this.connectionManager = multiThreadedHttpConnectionManager;
this.initialHttpState = initialHttpState;
}
/**
* Resets the http client state between requests,
* this is not necessarily required but might be a good idea
*/
public void resetState() {
if (initialHttpState != null) {
httpClient.setState(initialHttpState);
} else {
httpClient.setState( new HttpState() );
}
}
/**
* This is meant for system use so you should not be constructing this,
* use the {@link HttpRESTUtils#makeReusableHttpClient(boolean, int, javax.servlet.http.Cookie[])} instead
*/
public HttpClientWrapper(HttpClient httpClient,
MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager,
HttpState initialHttpState) {
super();
this.httpClient = httpClient;
this.connectionManager = multiThreadedHttpConnectionManager;
this.initialHttpState = initialHttpState;
}
/**
* Resets the http client state between requests,
* this is not necessarily required but might be a good idea
*/
public void resetState() {
if (initialHttpState != null) {
httpClient.setState(initialHttpState);
} else {
httpClient.setState( new HttpState() );
}
}
public static void setProxyHost(HttpClient httpClient, UsernamePasswordCredentials proxyCredentials,
String proxyHost, int proxyPort) {
if (proxyHost != null && !proxyHost.isEmpty()) {
httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
if (proxyCredentials != null) {
HttpState state = new HttpState();
state.setProxyCredentials(new AuthScope(proxyHost, proxyPort), proxyCredentials);
httpClient.setState(state);
}
}
}