use of org.apache.commons.httpclient.HttpException in project openhab1-addons by openhab.
the class FrontierSiliconRadioConnection method doRequest.
/**
* Performs a request to the radio with addition parameters.
*
* Typically used for changing parameters.
*
* @param REST
* API requestString, e.g. "SET/netRemote.sys.power"
* @param params
* , e.g. "value=1"
* @return request result
*/
public FrontierSiliconRadioApiResult doRequest(String requestString, String params) {
// 3 retries upon failure
for (int i = 0; i < 3; i++) {
if (!isLoggedIn && !doLogin()) {
// not logged in and login was not successful - try again!
continue;
}
final String url = "http://" + hostname + ":" + port + "/fsapi/" + requestString + "?pin=" + pin + "&sid=" + sessionId + (params == null || params.trim().length() == 0 ? "" : "&" + params);
logger.trace("calling url: '" + url + "'");
final HttpMethod method = new GetMethod(url);
method.getParams().setSoTimeout(SOCKET_TIMEOUT);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
try {
final int statusCode = httpClient.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
logger.warn("Method failed: " + method.getStatusLine());
isLoggedIn = false;
method.releaseConnection();
continue;
}
final String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
if (!responseBody.isEmpty()) {
logger.trace("got result: " + responseBody);
} else {
logger.debug("got empty result");
isLoggedIn = false;
method.releaseConnection();
continue;
}
final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody);
if (result.isStatusOk()) {
return result;
}
isLoggedIn = false;
method.releaseConnection();
// try again
continue;
} catch (HttpException he) {
logger.error("Fatal protocol violation: {}", he.toString());
isLoggedIn = false;
} catch (IOException ioe) {
logger.error("Fatal transport error: {}", ioe.toString());
} finally {
method.releaseConnection();
}
}
// 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?)
isLoggedIn = false;
return null;
}
use of org.apache.commons.httpclient.HttpException in project openhab1-addons by openhab.
the class AbstractRequest method executeUrl.
/**
* Executes the given <code>url</code> with the given <code>httpMethod</code>. In the case of httpMethods that do
* not support automatic redirection, manually handle the HTTP temporary redirect (307) and retry with the new URL.
*
* @param httpMethod
* the HTTP method to use
* @param url
* the url to execute (in milliseconds)
* @param contentString
* the content to be sent to the given <code>url</code> or <code>null</code> if no content should be
* sent.
* @param contentType
* the content type of the given <code>contentString</code>
* @return the response body or <code>NULL</code> when the request went wrong
*/
protected final String executeUrl(final String httpMethod, final String url, final String contentString, final String contentType) {
HttpClient client = new HttpClient();
HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
method.getParams().setSoTimeout(httpRequestTimeout);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
for (String httpHeaderKey : HTTP_HEADERS.stringPropertyNames()) {
method.addRequestHeader(new Header(httpHeaderKey, HTTP_HEADERS.getProperty(httpHeaderKey)));
}
// add content if a valid method is given ...
if (method instanceof EntityEnclosingMethod && contentString != null) {
EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
InputStream content = new ByteArrayInputStream(contentString.getBytes());
eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
}
if (logger.isDebugEnabled()) {
try {
logger.trace("About to execute '" + method.getURI().toString() + "'");
} catch (URIException e) {
logger.trace(e.getMessage());
}
}
try {
int statusCode = client.executeMethod(method);
if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
// perfectly fine but we cannot expect any answer...
return null;
}
// Manually handle 307 redirects with a little tail recursion
if (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
Header[] headers = method.getResponseHeaders("Location");
String newUrl = headers[headers.length - 1].getValue();
return executeUrl(httpMethod, newUrl, contentString, contentType);
}
if (statusCode != HttpStatus.SC_OK) {
logger.warn("Method failed: " + method.getStatusLine());
}
InputStream tmpResponseStream = method.getResponseBodyAsStream();
Header encodingHeader = method.getResponseHeader("Content-Encoding");
if (encodingHeader != null) {
for (HeaderElement ehElem : encodingHeader.getElements()) {
if (ehElem.toString().matches(".*gzip.*")) {
tmpResponseStream = new GZIPInputStream(tmpResponseStream);
logger.trace("GZipped InputStream from {}", url);
} else if (ehElem.toString().matches(".*deflate.*")) {
tmpResponseStream = new InflaterInputStream(tmpResponseStream);
logger.trace("Deflated InputStream from {}", url);
}
}
}
String responseBody = IOUtils.toString(tmpResponseStream);
if (!responseBody.isEmpty()) {
logger.trace(responseBody);
}
return responseBody;
} catch (HttpException he) {
logger.error("Fatal protocol violation: {}", he.toString());
} catch (IOException ioe) {
logger.error("Fatal transport error: {}", ioe.toString());
} finally {
method.releaseConnection();
}
return null;
}
use of org.apache.commons.httpclient.HttpException in project zaproxy by zaproxy.
the class ProxyThread method processHttp.
protected void processHttp(HttpRequestHeader requestHeader, boolean isSecure) throws IOException {
// ZAP: Replaced the class HttpBody with the class HttpRequestBody.
HttpRequestBody reqBody = null;
boolean isFirstRequest = true;
HttpMessage msg = null;
// reduce socket timeout after first read
inSocket.setSoTimeout(2500);
do {
if (isFirstRequest) {
isFirstRequest = false;
} else {
try {
requestHeader = httpIn.readRequestHeader(isSecure);
requestHeader.setSenderAddress(inSocket.getInetAddress());
} catch (SocketTimeoutException e) {
// ZAP: Log the exception
if (log.isDebugEnabled()) {
log.debug("Timed out while reading a new HTTP request.");
}
return;
}
}
if (parentServer.isEnableApi() && API.getInstance().handleApiRequest(requestHeader, httpIn, httpOut, isRecursive(requestHeader))) {
// It was an API request
return;
}
msg = new HttpMessage();
msg.setRequestHeader(requestHeader);
if (msg.getRequestHeader().getContentLength() > 0) {
// ZAP: Changed to call the method readRequestBody.
reqBody = httpIn.readRequestBody(requestHeader);
msg.setRequestBody(reqBody);
}
if (proxyParam.isRemoveUnsupportedEncodings()) {
removeUnsupportedEncodings(msg);
}
if (isProcessCache(msg)) {
continue;
}
if (parentServer.isSerialize()) {
semaphore = semaphoreSingleton;
} else {
semaphore = this;
}
boolean send = true;
synchronized (semaphore) {
if (notifyOverrideListenersRequestSend(msg)) {
send = false;
} else if (!notifyListenerRequestSend(msg)) {
// One of the listeners has told us to drop the request
return;
}
try {
// getHttpSender().sendAndReceive(msg, httpOut, buffer);
if (send) {
if (msg.getResponseHeader().isEmpty()) {
// Normally the response is empty.
// The only reason it wont be is if a script or other ext has deliberately 'hijacked' this request
// We dont jsut set send=false as this then means it wont appear in the History tab
getHttpSender().sendAndReceive(msg);
}
decodeResponseIfNeeded(msg);
if (!notifyOverrideListenersResponseReceived(msg)) {
if (!notifyListenerResponseReceive(msg)) {
// One of the listeners has told us to drop the response
return;
}
}
}
// notifyWrittenToForwardProxy();
} catch (HttpException e) {
// System.out.println("HttpException");
throw e;
} catch (SocketTimeoutException e) {
String message = Constant.messages.getString("proxy.error.readtimeout", msg.getRequestHeader().getURI(), connectionParam.getTimeoutInSecs());
log.warn(message);
setErrorResponse(msg, GATEWAY_TIMEOUT_RESPONSE_STATUS, message);
notifyListenerResponseReceive(msg);
} catch (IOException e) {
setErrorResponse(msg, BAD_GATEWAY_RESPONSE_STATUS, e);
notifyListenerResponseReceive(msg);
//throw e;
}
try {
writeHttpResponse(msg, httpOut);
} catch (IOException e) {
StringBuilder strBuilder = new StringBuilder(200);
strBuilder.append("Failed to write/forward the HTTP response to the client: ");
strBuilder.append(e.getClass().getName());
if (e.getMessage() != null) {
strBuilder.append(": ").append(e.getMessage());
}
log.warn(strBuilder.toString());
}
}
// release semaphore
ZapGetMethod method = (ZapGetMethod) msg.getUserObject();
keepSocketOpen = notifyPersistentConnectionListener(msg, inSocket, method);
if (keepSocketOpen) {
// do not wait for close
break;
}
} while (!isConnectionClose(msg) && !inSocket.isClosed());
}
use of org.apache.commons.httpclient.HttpException in project tdi-studio-se by Talend.
the class MDMTransactionClient method getSessionID.
public static String getSessionID(String url, String username, String password) throws IOException {
HttpClient client = new HttpClient();
client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
client.getParams().setAuthenticationPreemptive(true);
GetMethod get = new GetMethod(url);
get.setDoAuthentication(true);
String sessionID;
try {
client.executeMethod(get);
sessionID = parseSessionID(get);
} catch (HttpException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
get.releaseConnection();
}
return sessionID;
}
use of org.apache.commons.httpclient.HttpException in project tdi-studio-se by Talend.
the class MDMTransactionClient method newTransaction.
public static MDMTransaction newTransaction(String url, String username, String password) throws IOException {
HttpClient client = new HttpClient();
client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
client.getParams().setAuthenticationPreemptive(true);
PutMethod put = new PutMethod(url);
put.setDoAuthentication(true);
String tid;
String sessionID;
try {
client.executeMethod(put);
tid = put.getResponseBodyAsString();
sessionID = parseSessionID(put);
} catch (HttpException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
put.releaseConnection();
}
MDMTransaction result = new MDMTransaction();
result.setUrl(url);
result.setId(tid);
result.setUsername(username);
result.setPassword(password);
result.setSessionId(sessionID);
return result;
}
Aggregations