List of usage examples for org.apache.http.client ClientProtocolException ClientProtocolException
public ClientProtocolException(final Throwable cause)
From source file:org.apache.hawq.ranger.integration.service.tests.common.RESTClient.java
private String executeRequest(HttpUriRequest request) throws IOException { LOG.debug("--> request URI = " + request.getURI()); request.setHeader("Authorization", AUTH_HEADER); request.setHeader("Content-Type", ContentType.APPLICATION_JSON.toString()); CloseableHttpResponse response = httpClient.execute(request); String payload = null;/*w w w .ja v a2 s . co m*/ try { int responseCode = response.getStatusLine().getStatusCode(); LOG.debug("<-- response code = " + responseCode); HttpEntity entity = response.getEntity(); if (entity != null) { payload = EntityUtils.toString(response.getEntity()); } LOG.debug("<-- response payload = " + payload); if (responseCode == HttpStatus.SC_NOT_FOUND) { throw new ResourceNotFoundException(); } else if (responseCode >= 300) { throw new ClientProtocolException("Unexpected HTTP response code = " + responseCode); } } finally { response.close(); } return payload; }
From source file:ranktracker.crawler.google.SeoKeywordDetail.java
public static String fetchSemrushPage(String urlsrc) throws IOException { System.out.println("---------------Without Proxy-----------------"); CloseableHttpClient httpclient = HttpClients.createDefault(); String responseBody = ""; try {//from w ww .ja va 2 s. co m HttpGet httpget = new HttpGet(urlsrc); System.out.println("executing request " + httpget.getURI()); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status <= 600) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; responseBody = httpclient.execute(httpget, responseHandler); return responseBody; } catch (Exception e) { System.out.println("Exception in getting the sourec code from website :" + e); } finally { try { httpclient.close(); } catch (Exception e) { System.out.println("Exception " + e); } } return responseBody; }
From source file:org.sikuli.script.App.java
/** * issue a http(s) request//from w ww . j a v a 2s . c o m * @param url a valid url as used in a browser * @return textual content of the response or empty (UTF-8) * @throws IOException */ public static String wwwGet(String url) throws IOException { HttpGet httpget = new HttpGet(url); CloseableHttpResponse response = null; ResponseHandler rh = new ResponseHandler() { @Override public String handleResponse(final HttpResponse response) throws IOException { StatusLine statusLine = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } if (entity == null) { throw new ClientProtocolException("Response has no content"); } InputStream is = entity.getContent(); ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) != -1) { result.write(buffer, 0, length); } return result.toString("UTF-8"); } }; boolean oneTime = false; if (httpclient == null) { wwwStart(); oneTime = true; } Object content = httpclient.execute(httpget, rh); if (oneTime) { wwwStop(); } return (String) content; }
From source file:eu.eubrazilcc.lvl.storage.urlshortener.UrlShortener.java
private static final String loadShortenedUrl(final String url) throws Exception { String url2 = null, shortenedUrl = null; checkArgument(isNotBlank(url2 = trimToNull(url)), "Uninitialized or invalid url"); try (final TrustedHttpsClient httpClient = new TrustedHttpsClient()) { final ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { final int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { final HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); }//from w ww. j a v a 2s .c o m } }; final String response = httpClient.executePost( URL_SHORTENER + (isNotBlank(CONFIG_MANAGER.getGoogleAPIKey()) ? "?key=" + urlEncodeUtf8(CONFIG_MANAGER.getGoogleAPIKey()) : ""), ImmutableMap.of("Accept", "application/json", "Content-type", "application/json"), new StringEntity("{ \"longUrl\" : \"" + url2 + "\" }"), responseHandler); final Map<String, String> map = JSON_MAPPER.readValue(response, new TypeReference<HashMap<String, String>>() { }); checkState(map != null, "Server response is invalid"); shortenedUrl = map.get("id"); checkState(isNotBlank(shortenedUrl), "No shortened URL found in server response"); } return shortenedUrl; }
From source file:org.jenkinsci.plugins.newrelicnotifier.api.NewRelicClientImpl.java
/** * {@inheritDoc}/*from www . jav a 2 s .com*/ */ @Override public List<Application> getApplications(String apiKey) throws IOException { List<Application> result = new ArrayList<Application>(); URI url = null; try { url = new URI(API_URL + APPLICATIONS_ENDPOINT); } catch (URISyntaxException e) { // no need to handle this } HttpGet request = new HttpGet(url); setHeaders(request, apiKey); CloseableHttpClient client = getHttpClient(url); ResponseHandler<ApplicationList> rh = new ResponseHandler<ApplicationList>() { @Override public ApplicationList handleResponse(HttpResponse response) throws ClientProtocolException, IOException { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() != HttpStatus.SC_OK) { throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } HttpEntity entity = response.getEntity(); if (entity == null) { throw new ClientProtocolException("Response contains no content"); } Gson gson = new GsonBuilder().create(); Reader reader = new InputStreamReader(entity.getContent()); return gson.fromJson(reader, ApplicationList.class); } }; try { ApplicationList response = client.execute(request, rh); result.addAll(response.getApplications()); } finally { client.close(); } return result; }
From source file:net.shirayu.android.WlanLogin.MyHttpClient.java
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { AuthenticationHandler handler = client.getTargetAuthenticationHandler(); if (stop_auth && handler.isAuthenticationRequested(response, context)) { throw new ClientProtocolException("Authentication failed"); }//from w w w . ja va 2 s . c om }
From source file:es.ugr.swad.swadroid.webservices.RESTClient.java
public void sendRequest(Class<?> cl, boolean simple, REQUEST_TYPE type, JSONObject json) throws ClientProtocolException, SSLException, CertificateException, IOException, JSONException { Log.i(TAG, "Sending REST request (" + type + ") to " + SERVER + " and URL " + URL); switch (type) { case GET://w w w . j a v a 2 s.c o m result = RestEasy.doGet(URL); break; case POST: result = RestEasy.doPost(URL, json); break; case PUT: result = RestEasy.doPut(URL, json); break; case DELETE: result = false; RestEasy.doDelete(URL); result = true; break; default: throw new ClientProtocolException(type + " method not supported"); } if (!simple) { GsonBuilder gsonBuilder = new GsonBuilder(); // gsonBuilder.setDateFormat("M/d/yy hh:mm a"); Gson gson = gsonBuilder.create(); result = gson.fromJson(((JSONObject) result).toString(), cl); } }
From source file:org.jboss.arquillian.container.was.wlp_remote_8_5.WLPRestClient.java
/** * Uses the rest api to upload an application binary to the dropins folder * of WLP to allow the server automatically deploy it. * //from www .j a v a 2 s . c o m * @param archive * @throws ClientProtocolException * @throws IOException */ public void deploy(File archive) throws ClientProtocolException, IOException { if (log.isLoggable(Level.FINER)) { log.entering(className, "deploy"); } String deployPath = String.format("${wlp.user.dir}/servers/%s/dropins/%s", configuration.getServerName(), archive.getName()); 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.Post(serverRestEndpoint).useExpectContinue() .version(HttpVersion.HTTP_1_1).bodyFile(archive, ContentType.DEFAULT_BINARY)).returnResponse(); if (log.isLoggable(Level.FINE)) { log.fine("While deploying file " + archive.getName() + ", server returned response: " + result.getStatusLine().getStatusCode()); } if (!isSuccessful(result)) { throw new ClientProtocolException( "Could not deploy application to server, server returned response: " + result); } if (log.isLoggable(Level.FINER)) { log.exiting(className, "deploy"); } }
From source file:ac.uk.diamond.sample.HttpClientTest.Utils.java
/** * Helper method that deserializes and unmarshalls the message from the given stream. This * method has been adapted from {@code org.opensaml.ws.message.decoder.BaseMessageDecoder}. * //from w w w . ja v a2 s . c om * @param messageStream * input stream containing the message * * @return the inbound message * * @throws MessageDecodingException * thrown if there is a problem deserializing and unmarshalling the message */ static XMLObject unmarshallMessage(ParserPool parserPool, String messageStream) throws ClientProtocolException { try { Document messageDoc = parserPool.parse(new StringReader(messageStream)); Element messageElem = messageDoc.getDocumentElement(); Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(messageElem); if (unmarshaller == null) { throw new ClientProtocolException( "Unable to unmarshall message, no unmarshaller registered for message element " + XMLHelper.getNodeQName(messageElem)); } XMLObject message = unmarshaller.unmarshall(messageElem); return message; } catch (XMLParserException e) { throw new ClientProtocolException("Encountered error parsing message into its DOM representation", e); } catch (UnmarshallingException e) { throw new ClientProtocolException("Encountered error unmarshalling message from its DOM representation", e); } }
From source file:swp.bibclient.Network.java
/** * Fragt bei einem Server nach den Medien an. * * @return Die Liste der Medien.//from www.j av a2 s .com * @throws IOException * Kann geworfen werden bei IO-Problemen. */ public final List<Medium> getMediums() throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); // Setzen eines ConnectionTimeout von 2 Sekunden: HttpParams params = httpClient.getParams(); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); httpClient.setParams(params); // Der BibServer sollte lokal laufen, daher zugriff auf Localhost // 10.0.2.2 fr den AndroidEmulator. HttpContext localContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet(server + mediumpath); String text = null; Log.i(Network.class.getName(), "Try to get a http connection..."); HttpResponse response = httpClient.execute(httpGet, localContext); HttpEntity entity = response.getEntity(); text = getASCIIContentFromEntity(entity); Log.i(Network.class.getName(), "Create new Gson object"); Gson gson = new Gson(); Log.i(Network.class.getName(), "Create listOfTestObject"); // Wir arbeiten mit einem TypeToken um fr eine generische Liste wieder // Objekte zu erhalten. Type listOfTestObject = new TypeToken<List<Medium>>() { }.getType(); Log.i(Network.class.getName(), "Convert to a list."); /* * Hier befindet sich ein unsicherer Cast, da wir nicht wirklich wissen, * ob der String, den wir von der Website bekommen, sich wirklich in * eine Liste von Bchern umwandeln lsst */ try { @SuppressWarnings("unchecked") List<Medium> list = Collections.synchronizedList((List<Medium>) gson.fromJson(text, listOfTestObject)); return list; } catch (ClassCastException e) { throw new ClientProtocolException("Returned type is not a list of book objects"); } }