use of org.apache.http.client.ClientProtocolException in project openhab1-addons by openhab.
the class StreamClientImpl method sendRequest.
@Override
public StreamResponseMessage sendRequest(StreamRequestMessage requestMessage) {
final UpnpRequest requestOperation = requestMessage.getOperation();
log.fine("Preparing HTTP request message with method '" + requestOperation.getHttpMethodName() + "': " + requestMessage);
try {
// Create the right HTTP request
HttpUriRequest httpRequest = createHttpRequest(requestMessage, requestOperation);
// Set all the headers on the request
httpRequest.setParams(getRequestParams(requestMessage));
HeaderUtil.add(httpRequest, requestMessage.getHeaders());
log.fine("Sending HTTP request: " + httpRequest.getURI());
return httpClient.execute(httpRequest, createResponseHandler());
} catch (MethodNotSupportedException ex) {
log.warning("Request aborted: " + ex.toString());
return null;
} catch (ClientProtocolException ex) {
log.warning("HTTP protocol exception executing request: " + requestMessage);
log.warning("Cause: " + Exceptions.unwrap(ex));
return null;
} catch (IOException ex) {
// Don't log stacktrace
log.fine("Client connection was aborted: " + ex.getMessage());
return null;
}
}
use of org.apache.http.client.ClientProtocolException in project opennms by OpenNMS.
the class NCSNorthbounder method postAlarms.
private void postAlarms(HttpEntity entity) {
// Need a configuration bean for these
int connectionTimeout = 3000;
int socketTimeout = 3000;
Integer retryCount = 3;
HttpVersion httpVersion = determineHttpVersion(m_config.getHttpVersion());
URI uri = m_config.getURI();
System.err.println("uri = " + uri);
final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setSocketTimeout(socketTimeout).setConnectionTimeout(connectionTimeout).setRetries(retryCount).useBrowserCompatibleCookies().dontReuseConnections();
if ("https".equals(uri.getScheme())) {
try {
clientWrapper.useRelaxedSSL("https");
} catch (final GeneralSecurityException e) {
throw new NorthbounderException("Failed to configure Relaxed SSL handling.", e);
}
}
final HttpEntityEnclosingRequestBase method = m_config.getMethod().getRequestMethod(uri);
if (m_config.getVirtualHost() != null && !m_config.getVirtualHost().trim().isEmpty()) {
method.setHeader(HTTP.TARGET_HOST, m_config.getVirtualHost());
}
if (m_config.getUserAgent() != null && !m_config.getUserAgent().trim().isEmpty()) {
method.setHeader(HTTP.USER_AGENT, m_config.getUserAgent());
}
method.setProtocolVersion(httpVersion);
method.setEntity(entity);
CloseableHttpResponse response = null;
try {
System.err.println("execute: " + method);
response = clientWrapper.execute(method);
} catch (ClientProtocolException e) {
throw new NorthbounderException(e);
} catch (IOException e) {
throw new NorthbounderException(e);
} finally {
IOUtils.closeQuietly(clientWrapper);
}
if (response != null) {
try {
int code = response.getStatusLine().getStatusCode();
final HttpResponseRange range = new HttpResponseRange("200-399");
if (!range.contains(code)) {
LOG.warn("response code out of range for uri: {}. Expected {} but received {}", uri, range, code);
throw new NorthbounderException("response code out of range for uri:" + uri + ". Expected " + range + " but received " + code);
}
} finally {
IOUtils.closeQuietly(clientWrapper);
}
}
LOG.debug(response != null ? response.getStatusLine().getReasonPhrase() : "Response was null");
}
use of org.apache.http.client.ClientProtocolException in project android-garage-opener by bradfitz.
the class InRangeService method openGarage.
// Returns true if the HTTP request was started.
private boolean openGarage() {
if (!shouldOpen.get()) {
Log.e(TAG, "openGarage() called but shouldOpen isn't true");
stopMobileData();
return false;
}
if (!httpRequestOustanding.compareAndSet(false, true)) {
Log.d(TAG, "Not opening garage door due to other outstanding HTTP request.");
stopMobileData();
return false;
}
final String urlBase = getPrefs().getString(Preferences.KEY_URL, null);
if (urlBase == null) {
Log.e(TAG, "No garage door URL configured.");
return false;
}
final String secretKey = getPrefs().getString(Preferences.KEY_SECRET, "");
// We already did this before, but it might not have set the set
// the route, if it was still enabling the 3G connection. We do it again
// which is likely a no-op, but might cause the route to be created.
forceMobileConnection();
final HttpClient client = new DefaultHttpClient();
Date now = new Date();
long epochTime = now.getTime() / 1000;
String url = urlBase + "?t=" + epochTime + "&key=" + hmacSha1("" + epochTime, secretKey);
Log.d(TAG, "Attempting open of: " + urlBase);
logToClients("Sending HTTP request to " + url);
final HttpUriRequest request = new HttpGet(url);
Runnable httpRunnable = new Runnable() {
public void run() {
try {
client.execute(request, new ResponseHandler<HttpResponse>() {
public HttpResponse handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
if (response.getStatusLine().getStatusCode() == 200) {
doNotification("Garage Opened", "The garage door was opened.");
logToClients("HTTP success. Opened.");
// done.
shouldOpen.set(false);
} else {
notifyError("HTTP error: " + response.toString());
}
httpRequestOustanding.set(false);
return response;
}
});
} catch (ClientProtocolException e) {
notifyError("ClientProtocolException = " + e);
e.printStackTrace();
retryOpenGarageSoon();
} catch (IOException e) {
notifyError("IOException = " + e);
e.printStackTrace();
retryOpenGarageSoon();
} finally {
httpRequestOustanding.set(false);
stopMobileData();
}
}
};
Thread httpThread = new Thread(httpRunnable);
httpThread.start();
return true;
}
use of org.apache.http.client.ClientProtocolException in project weixin-java-tools by chanjarster.
the class WxCpServiceImpl method getAccessToken.
public String getAccessToken(boolean forceRefresh) throws WxErrorException {
if (forceRefresh) {
wxCpConfigStorage.expireAccessToken();
}
if (wxCpConfigStorage.isAccessTokenExpired()) {
synchronized (globalAccessTokenRefreshLock) {
if (wxCpConfigStorage.isAccessTokenExpired()) {
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?" + "&corpid=" + wxCpConfigStorage.getCorpId() + "&corpsecret=" + wxCpConfigStorage.getCorpSecret();
try {
HttpGet httpGet = new HttpGet(url);
if (httpProxy != null) {
RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build();
httpGet.setConfig(config);
}
CloseableHttpClient httpclient = getHttpclient();
String resultContent = null;
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
resultContent = new BasicResponseHandler().handleResponse(response);
}
WxError error = WxError.fromJson(resultContent);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
WxAccessToken accessToken = WxAccessToken.fromJson(resultContent);
wxCpConfigStorage.updateAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn());
} catch (ClientProtocolException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
return wxCpConfigStorage.getAccessToken();
}
use of org.apache.http.client.ClientProtocolException in project weixin-java-tools by chanjarster.
the class WxCpServiceImpl method executeInternal.
protected synchronized <T, E> T executeInternal(RequestExecutor<T, E> executor, String uri, E data) throws WxErrorException {
if (uri.indexOf("access_token=") != -1) {
throw new IllegalArgumentException("uri参数中不允许有access_token: " + uri);
}
String accessToken = getAccessToken(false);
String uriWithAccessToken = uri;
uriWithAccessToken += uri.indexOf('?') == -1 ? "?access_token=" + accessToken : "&access_token=" + accessToken;
try {
return executor.execute(getHttpclient(), httpProxy, uriWithAccessToken, data);
} catch (WxErrorException e) {
WxError error = e.getError();
/*
* 发生以下情况时尝试刷新access_token
* 40001 获取access_token时AppSecret错误,或者access_token无效
* 42001 access_token超时
*/
if (error.getErrorCode() == 42001 || error.getErrorCode() == 40001) {
// 强制设置wxCpConfigStorage它的access token过期了,这样在下一次请求里就会刷新access token
wxCpConfigStorage.expireAccessToken();
return execute(executor, uri, data);
}
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
return null;
} catch (ClientProtocolException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Aggregations