List of usage examples for org.apache.http.client ClientProtocolException ClientProtocolException
public ClientProtocolException(final Throwable cause)
From source file:com.example.restexpmongomvn.controller.VehicleControllerTest.java
/** * Test of read method, of class VehicleController. * @throws com.fasterxml.jackson.core.JsonProcessingException * @throws java.io.IOException//from www. j a v a 2 s . co m */ @Test public void testRead() throws JsonProcessingException, IOException { System.out.println("read"); Vehicle testVehicle = new Vehicle(2015, "Test", "Vehicle", Color.Red, "4-Door Sedan"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(Include.NON_EMPTY); String testVehicleString = objectMapper.writeValueAsString(testVehicle); StringEntity postEntity = new StringEntity(testVehicleString, ContentType.create("application/json", "UTF-8")); postEntity.setChunked(true); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(BASE_URL + "/restexpress/vehicles"); httppost.setEntity(postEntity); CloseableHttpResponse response = httpclient.execute(httppost); String responseString = new BasicResponseHandler().handleResponse(response); responseString = responseString.replaceAll("^\"|\"$", ""); // Get vehicle based on MongoDB id HttpGet httpget = new HttpGet(BASE_URL + "/restexpress/vehicle/" + responseString); CloseableHttpResponse response2 = httpclient.execute(httpget); String responseString2 = new BasicResponseHandler().handleResponse(response2); ResponseHandler<Vehicle> rh = new ResponseHandler<Vehicle>() { @Override public Vehicle 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 contains no content"); } Gson gson = new GsonBuilder().setPrettyPrinting().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .create(); ContentType contentType = ContentType.getOrDefault(entity); Charset charset = contentType.getCharset(); Reader reader = new InputStreamReader(entity.getContent(), "UTF-8"); // String inputStreamString = new Scanner(entity.getContent(), "UTF-8").useDelimiter("\\A").next(); // System.out.println(inputStreamString); return gson.fromJson(reader, Vehicle.class); } }; Vehicle vehicle = httpclient.execute(httpget, rh); System.out.println("b"); // MongodbEntityRepository<Vehicle> vehicleRepository; // VehicleController instance = new VehicleController(vehicleRepository); // Vehicle result = instance.read(request, response); // assertEquals(parseMongoId(responseString), true); }
From source file:com.apigee.sdk.apm.http.impl.client.cache.ResponseProtocolCompliance.java
private void unauthorizedResponseDidNotHaveAWWWAuthenticateHeader(HttpRequest request, HttpResponse response) throws ClientProtocolException { if (response.getStatusLine().getStatusCode() != HttpStatus.SC_UNAUTHORIZED) return;/*from ww w.j a v a 2 s . c o m*/ if (response.getFirstHeader(HeaderConstants.WWW_AUTHENTICATE) == null) { throw new ClientProtocolException( "401 Response did not contain required WWW-Authenticate challenge header"); } }
From source file:de.lemo.apps.restws.client.InitialisationImpl.java
public Boolean defaultConnectionCheck() throws RestServiceCommunicationException { try {//w w w.jav a 2 s. co m // not a proxy object because we want to get the http status ClientRequest request = new ClientRequest(InitialisationImpl.SERVICE_STARTTIME_URL, clientExecutor); ClientResponse<ServiceStartTime> response = request.get(ServiceStartTime.class); if (response.getStatus() != HttpStatus.SC_OK) { throw new ClientProtocolException( "Default Connection Check: Failed : HTTP error code : " + response.getStatus()); } response.releaseConnection(); return true; } catch (final Exception e) { throw new RestServiceCommunicationException(this.toString() + " " + e.getLocalizedMessage()); } }
From source file:sample.ui.mvc.MessageController.java
private String getBidMima(String bidId) { // bidId = "346"; String url = "http://wujinsuo.cn/index.php?ctl=deal&id=" + bidId + "&act=bid"; String mima = ""; try {// w ww.ja v a 2 s . c om BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); doLogin(cookieStore, httpclient, ZHANGDAIYIXIAN); HttpGet httpget = new HttpGet(url); httpget.addHeader("Accept", ACCEPT); httpget.addHeader("User-Agent", AGENT); 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 resultString = httpclient.execute(httpget, responseHandler); int index = resultString.indexOf("#mima\").val())!="); mima = resultString.substring(index + 16, index + 20); logger.info(mima); } catch (Exception e) { e.printStackTrace(); } return mima; }
From source file:se.berazy.api.client.PoSInvoiceClient.java
/** * Sends a POST request.//from w w w .ja v a 2 s .c o m * * @param object * @throws ClientProtocolException * @throws IOException */ <TRequest, TResponse> TResponse sendRequest(String url, JAXBElement<TRequest> requestObject, Class<TResponse> responseObject) throws IOException, ClientProtocolException { loadProperties(); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); String key = EncryptionUtils.hash((getIpAddress() + formatter.format(new Date()) + getAuthToken())); httpPost.addHeader("accept", "application/xml"); httpPost.addHeader("customerNo", getCustomerNo().toString()); httpPost.addHeader("key", key); try { String data = XmlUtils.serialize(requestObject); StringEntity stringEntity = new StringEntity(data); stringEntity.setContentType("application/xml"); stringEntity.setContentEncoding("UTF-8"); httpPost.setEntity(stringEntity); log.debug(String.format("XML request: ", data)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { InputStream is = response.getEntity().getContent(); return XmlUtils.deserialize(is, responseObject); } catch (IOException e) { throw e; } catch (RuntimeException e) { httpPost.abort(); throw e; } finally { try { instream.close(); } catch (Exception e) { log.warn("Cannot close response stream.", e); } } } else { throw new ClientProtocolException("Response contains no content"); } } catch (JAXBException e) { throw new ClientProtocolException("Malformed XML", e); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:org.neo4j.ogm.drivers.http.request.HttpRequest.java
public static CloseableHttpResponse execute(CloseableHttpClient httpClient, HttpRequestBase request, Credentials credentials) throws HttpRequestException { LOGGER.debug("Thread: {}, request: {}", Thread.currentThread().getId(), request); CloseableHttpResponse response;/*from w w w. jav a 2s . c o m*/ request.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8")); request.setHeader(new BasicHeader(HTTP.USER_AGENT, "neo4j-ogm.java/2.0")); request.setHeader(new BasicHeader("Accept", "application/json;charset=UTF-8")); HttpAuthorization.authorize(request, credentials); // use defaults: 3 retries, 2 second wait between attempts RetryOnExceptionStrategy retryStrategy = new RetryOnExceptionStrategy(); while (retryStrategy.shouldRetry()) { try { response = httpClient.execute(request); StatusLine statusLine = response.getStatusLine(); HttpEntity responseEntity = response.getEntity(); if (statusLine.getStatusCode() >= 300) { String responseText = statusLine.getReasonPhrase(); if (responseEntity != null) { responseText = parseError(EntityUtils.toString(responseEntity)); LOGGER.warn("Thread: {}, response: {}", Thread.currentThread().getId(), responseText); } throw new HttpResponseException(statusLine.getStatusCode(), responseText); } if (responseEntity == null) { throw new ClientProtocolException("Response contains no content"); } return response; // don't close response yet, it is not consumed! } // if we didn't get a response at all, try again catch (NoHttpResponseException nhre) { LOGGER.warn("Thread: {}, No response from server: Retrying in {} milliseconds, retries left: {}", Thread.currentThread().getId(), retryStrategy.getTimeToWait(), retryStrategy.numberOfTriesLeft); retryStrategy.errorOccurred(); } catch (RetryException re) { throw new HttpRequestException(request, re); } catch (ClientProtocolException uhe) { throw new ConnectionException(request.getURI().toString(), uhe); } catch (IOException ioe) { throw new HttpRequestException(request, ioe); } // here we catch any exception we throw above (plus any we didn't throw ourselves), // log the problem, close any connection held by the request // and then rethrow the exception to the caller. catch (Exception exception) { LOGGER.warn("Thread: {}, exception: {}", Thread.currentThread().getId(), exception.getCause().getLocalizedMessage()); request.releaseConnection(); throw exception; } } throw new RuntimeException("Fatal Exception: Should not have occurred!"); }
From source file:com.apigee.sdk.apm.http.impl.client.cache.ResponseProtocolCompliance.java
private void ensurePartialContentIsNotSentToAClientThatDidNotRequestIt(HttpRequest request, HttpResponse response) throws ClientProtocolException { if (request.getFirstHeader(HeaderConstants.RANGE) != null) return;/*w ww. j ava 2 s .c o m*/ if (response.getFirstHeader(HeaderConstants.CONTENT_RANGE) != null) { throw new ClientProtocolException( "Content-Range was returned for a request that did not ask for a Content-Range."); } }
From source file:com.att.voice.AttDigitalLife.java
public String getAttribute(Map<String, String> authMap, String deviceGUID, String attribute) { try {/*w w w . j a va 2s . c om*/ URIBuilder builder = new URIBuilder(); builder.setScheme("https").setHost(DIGITAL_LIFE_PATH) .setPath("/penguin/api/" + authMap.get("id") + "/devices/" + deviceGUID + "/" + attribute); 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 content = new JSONObject(json); return content.getJSONObject("content").getString("value"); } catch (URISyntaxException | IOException | JSONException ex) { System.err.println(ex.getMessage()); return null; } }
From source file:com.thed.zapi.cloud.sample.CreateCycleAndAddTests.java
public String addTestsToCycle(String uriStr, ZFJCloudRestClient client, String accessKey, StringEntity addTestsJSON)//from w ww. j av a 2 s. c o m throws URISyntaxException, JSONException, IllegalStateException, IOException { URI uri = new URI(uriStr); int expirationInSec = 360; JwtGenerator jwtGenerator = client.getJwtGenerator(); String jwt = jwtGenerator.generateJWT("POST", uri, expirationInSec); System.out.println(uri.toString()); System.out.println(jwt); HttpResponse response = null; HttpClient restClient = new DefaultHttpClient(); HttpPost addTestsReq = new HttpPost(uri); addTestsReq.addHeader("Content-Type", "application/json"); addTestsReq.addHeader("Authorization", jwt); addTestsReq.addHeader("zapiAccessKey", accessKey); addTestsReq.setEntity(addTestsJSON); try { response = restClient.execute(addTestsReq); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int statusCode = response.getStatusLine().getStatusCode(); System.out.println(statusCode); System.out.println(response.toString()); String string = null; if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = response.getEntity(); try { string = EntityUtils.toString(entity); //System.out.println(string); JSONObject cycleObj = new JSONObject(entity); //System.out.println(cycleObj.toString()); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { try { throw new ClientProtocolException("Unexpected response status: " + statusCode); } catch (ClientProtocolException e) { e.printStackTrace(); } } return string; }
From source file:org.dataconservancy.ui.services.EZIDServiceImplTest.java
/** * Tests exceptional conditions when calling the save method, including bad return code and unexpect return format * @throws ClientProtocolException/* ww w. j a v a 2s . c o m*/ * @throws IOException */ @Test public void testSaveExceptions() throws ClientProtocolException, IOException { HttpResponse mockResponse = new BasicHttpResponse(new HttpVersion(1, 1), 200, "ok"); StringEntity entity = new StringEntity("success: namespace:id"); mockResponse.setEntity(entity); HttpClient mockHttpClient = mock(HttpClient.class); when(mockHttpClient.execute(any(HttpPost.class))) .thenThrow(new ClientProtocolException("Expected exception")); ezidService.setHttpClient(mockHttpClient); boolean caughtException = false; try { ezidService.saveID("www.test.com/id/namespace:id"); } catch (EZIDServiceException e) { caughtException = true; assertEquals("org.apache.http.client.ClientProtocolException: Expected exception", e.getMessage()); } assertTrue(caughtException); mockResponse = new BasicHttpResponse(new HttpVersion(1, 1), 404, "not found"); mockResponse.setEntity(entity); mockHttpClient = mock(HttpClient.class); when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(mockResponse); ezidService.setHttpClient(mockHttpClient); caughtException = false; try { ezidService.saveID("www.test.com/id/namespace:id"); } catch (EZIDServiceException e) { caughtException = true; assertTrue(e.getMessage().contains("not found")); } assertTrue(caughtException); mockResponse = new BasicHttpResponse(new HttpVersion(1, 1), 200, "ok"); entity = new StringEntity("namespace:id"); mockResponse.setEntity(entity); mockHttpClient = mock(HttpClient.class); when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(mockResponse); ezidService.setHttpClient(mockHttpClient); caughtException = false; try { ezidService.saveID("www.test.com/id/namespace:id"); } catch (EZIDServiceException e) { caughtException = true; assertEquals("Unexpected response: namespace:id", e.getMessage()); } assertTrue(caughtException); }