List of usage examples for org.apache.http.client ClientProtocolException ClientProtocolException
public ClientProtocolException(final Throwable cause)
From source file:com.vsct.dt.strowgr.admin.repository.consul.ConsulReader.java
/** * Read HttpResponse into HttpEntity and apply method with the result. * If result http status is not between 200 and 299, an exception is raised * * @param httpResponse response to read/*from ww w. j av a 2 s. co m*/ * @param method method to apply to the read result * @param accept404 whether to return or not an empty result if a 404 occurs * @param <T> Type of the method application * @return the result of the method application. The result is not nullable. * @throws ClientProtocolException thrown if the http status is not between 200 and 299 including */ private <T> Optional<T> parseHttpResponse(HttpResponse httpResponse, Function<HttpEntity, Optional<T>> method, boolean accept404) throws ClientProtocolException { int status = httpResponse.getStatusLine().getStatusCode(); HttpEntity entity = httpResponse.getEntity(); Optional<T> result = Optional.empty(); if (status >= 200 && status < 300) { result = method.apply(entity); } else if (status != 404 || !accept404) { String content = Optional.ofNullable(entity).map(myEntity -> { try { return EntityUtils.toString(myEntity); } catch (IOException e) { LOGGER.error("can't parse content from consul", e); return null; } }).orElse("no content"); throw new ClientProtocolException("Unexpected response status: " + status + ": " + httpResponse.getStatusLine().getReasonPhrase() + ", entity is " + content); } return result; }
From source file:org.muhia.app.psi.config.http.CustomHttpClientUtilities.java
public String doGetWithResponseHandler(String url) { String result;/* w w w. j av a 2s . c o m*/ // CloseableHttpResponse response = null; CloseableHttpClient client = null; try { RequestConfig config = RequestConfig.custom().setConnectTimeout(hcp.getConnectionTimeout()) .setConnectionRequestTimeout(hcp.getConnectionRequestTimeout()) .setSocketTimeout(hcp.getSockectTimeout()).build(); client = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); HttpGet getMethod = new HttpGet(url); ResponseHandler<String> responseHandler = (final HttpResponse response) -> { int status = response.getStatusLine().getStatusCode(); if (status >= hcp.getLowerStatusLimit() && status <= hcp.getUpperStatusLimit()) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException(hcp.getExceptionMessage() + status); } }; result = client.execute(getMethod, responseHandler); client.close(); } catch (SocketTimeoutException ex) { result = hcp.getTimeoutMessage(); Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { result = hcp.getFailMessage(); Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (client != null) { client.close(); } } catch (IOException ex) { Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex); } } return result; }
From source file:org.yamj.core.tools.web.PoolingHttpClient.java
private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException { HttpHost target = null;/*from ww w.j a va2 s .c om*/ URI requestURI = request.getURI(); if (requestURI.isAbsolute()) { target = URIUtils.extractHost(requestURI); if (target == null) { throw new ClientProtocolException("URI does not specify a valid host name: " + requestURI); } } return target; }
From source file:net.shirayu.android.WlanLogin.MyHttpClient.java
public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException, ClientProtocolException { stop_auth = false;//www . j av a 2 s . c o m try { return client.execute(target, request); } catch (RuntimeException ex) { throw new ClientProtocolException(ex.getMessage()); } }
From source file:com.att.voice.AttDigitalLife.java
public String getDeviceGUID(String device, Map<String, String> authMap) { try {// w w w . ja v a 2 s.c om URIBuilder builder = new URIBuilder(); builder.setScheme("https").setHost(DIGITAL_LIFE_PATH) .setPath("/penguin/api/" + authMap.get("id") + "/devices"); URI uri = builder.build(); HttpGet httpget = new HttpGet(uri); httpget.setHeader("Authtoken", authMap.get("Authtoken")); httpget.setHeader("Requesttoken", authMap.get("Requesttoken")); httpget.setHeader("Appkey", authMap.get("Appkey")); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpclient.execute(httpget, responseHandler); String json = responseBody.trim(); JSONObject jsonObject = new JSONObject(json); JSONArray array = jsonObject.getJSONArray("content"); for (int i = 0; i <= array.length(); i++) { JSONObject d = array.getJSONObject(i); String type = d.getString("deviceType"); if (type.equalsIgnoreCase(device)) { return d.getString("deviceGuid"); } } } catch (URISyntaxException | IOException | JSONException ex) { System.err.println(ex.getMessage()); return null; } return null; }
From source file:com.trickl.crawler.protocol.http.HttpProtocol.java
@Override public ManagedContentEntity load(URI uri) throws IOException { HttpRequestBase httpRequest;/*from ww w .j ava 2s . c o m*/ if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) { HttpPost httpPost = new HttpPost(uri); // Add header data for (Map.Entry<String, String> headerDataEntry : headerData.entrySet()) { httpPost.setHeader(headerDataEntry.getKey(), headerDataEntry.getValue()); } // Add post data String contentType = headerData.get("Content-Type"); if (contentType == null || "application/x-www-form-urlencoded".equalsIgnoreCase(contentType)) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, Object> postDataEntry : postData.entrySet()) { nameValuePairs.add( new BasicNameValuePair(postDataEntry.getKey(), postDataEntry.getValue().toString())); } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } else if ("application/json".equalsIgnoreCase(contentType)) { ObjectMapper mapper = new ObjectMapper(); StringEntity se; try { String jsonString = mapper.writeValueAsString(postData); se = new StringEntity(jsonString); httpPost.setEntity(se); } catch (JsonGenerationException ex) { log.error("Failed to generate JSON.", ex); } catch (JsonMappingException ex) { log.error("Failed to generate JSON.", ex); } } httpRequest = httpPost; } else { httpRequest = new HttpGet(uri); } HttpResponse response = httpclient.execute(httpRequest); StatusLine statusline = response.getStatusLine(); if (statusline.getStatusCode() >= HttpStatus.SC_BAD_REQUEST) { httpRequest.abort(); throw new HttpResponseException(statusline.getStatusCode(), statusline.getReasonPhrase()); } HttpEntity entity = response.getEntity(); if (entity == null) { // Should _almost_ never happen with HTTP GET requests. throw new ClientProtocolException("Empty entity"); } long maxlen = httpclient.getParams().getLongParameter(DroidsHttpClient.MAX_BODY_LENGTH, 0); return new HttpContentEntity(entity, maxlen); }
From source file:net.shirayu.android.WlanLogin.MyHttpClient.java
public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> handler) throws IOException, ClientProtocolException { stop_auth = false;/*w w w .ja v a2s . c o m*/ try { return client.execute(request, handler); } catch (RuntimeException ex) { throw new ClientProtocolException(ex.getMessage()); } }
From source file:com.google.android.net.GoogleHttpClient.java
/** * Wraps the request making it mutable./* w w w.j av a 2 s.co m*/ */ private static RequestWrapper wrapRequest(HttpUriRequest request) throws IOException { try { // We have to wrap it with the right type. Some code performs // instanceof checks. RequestWrapper wrapped; if (request instanceof HttpEntityEnclosingRequest) { wrapped = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request); } else { wrapped = new RequestWrapper(request); } // Copy the headers from the original request into the wrapper. wrapped.resetHeaders(); return wrapped; } catch (ProtocolException e) { throw new ClientProtocolException(e); } }
From source file:org.jboss.arquillian.container.was.wlp_remote_8_5.WLPRestClient.java
/** * Deletes the specified application from the servers dropins directory. WLP * will detect this and then undeploy it. * /*from w w w . j a va 2 s .c om*/ * @param String * - applicationName * @throws ClientProtocolException * @throws IOException */ public void undeploy(String applicationName) throws ClientProtocolException, IOException { if (log.isLoggable(Level.FINER)) { log.entering(className, "undeploy"); } String deployPath = String.format("${wlp.user.dir}/servers/%s/dropins/%s", configuration.getServerName(), applicationName); String serverRestEndpoint = String.format("https://%s:%d%s%s", configuration.getHostName(), configuration.getHttpsPort(), FILE_ENDPOINT, URLEncoder.encode(deployPath, UTF_8)); HttpResponse result = executor .execute(Request.Delete(serverRestEndpoint).useExpectContinue().version(HttpVersion.HTTP_1_1)) .returnResponse(); if (isSuccessful(result)) { log.fine("File " + applicationName + " was deleted"); } else { throw new ClientProtocolException("Unable to undeploy application " + applicationName + ", server returned response: " + result.getStatusLine()); } if (log.isLoggable(Level.FINER)) { log.exiting(className, "undeploy", result); } }
From source file:com.codspire.mojo.artifactlookup.ProcessResponse.java
/** * /* w w w.j a va2 s . c o m*/ * @param sha1Checksum * @return */ public GAV lookupRepo(String sha1Checksum) { String url = apiEndpoint + sha1Checksum; log.debug("Request URL: " + url); HttpGet httpGet = new HttpGet(url); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = null; GAV gav; try (CloseableHttpClient httpclient = HttpClients.createDefault()) { responseBody = httpclient.execute(httpGet, responseHandler); if (log.isDebugEnabled()) { log.debug("----------------------------------------"); log.debug(responseBody); log.debug("----------------------------------------"); } gav = getGAV(responseBody); if (log.isDebugEnabled()) { log.debug(gav.toString()); } } catch (Exception e) { throw new ContextedRuntimeException("Unable to get the http response: " + url, e); } if (gav == null || gav.isIncomlete()) { throw new ContextedRuntimeException("No GAV found for " + sha1Checksum); } return gav; }