private void checkHttpResponseStatus(HttpResponse response) { if (response.getStatusLine().getStatusCode() == 200) { return; } StatusLine status = response.getStatusLine(); String message = ""; try { message = EntityUtils.toString(response.getEntity()); } catch (IOException e) { //ignore } throw new ApolloOpenApiException(status.getStatusCode(), status.getReasonPhrase(), message); }
/** * Send an encoded string to the Eventhub using post method */ private int request (String encoded) throws IOException { refreshSignature(); HttpPost httpPost = new HttpPost(targetURI); httpPost.setHeader("Content-type", "application/vnd.microsoft.servicebus.json"); httpPost.setHeader("Authorization", signature); httpPost.setHeader("Host", namespaceName + ".servicebus.windows.net "); StringEntity entity = new StringEntity(encoded); httpPost.setEntity(entity); HttpResponse response = httpclient.execute(httpPost); StatusLine status = response.getStatusLine(); HttpEntity entity2 = response.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity2); int returnCode = status.getStatusCode(); if (returnCode != HttpStatus.SC_CREATED) { LOG.error (new IOException(status.getReasonPhrase()).toString()); throw new IOException(status.getReasonPhrase()); } return returnCode; }
.setSocketTimeout(timeout) .build(); HttpGet httpGet = new HttpGet(uri); HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(config); CloseableHttpResponse response = httpclient.execute(httpGet, context); try { int statusCode = response.getStatusLine().getStatusCode(); long end = System.currentTimeMillis(); long cost = end - start; return EntityUtils.toByteArray(response.getEntity()); } else { String errorMsg = EntityUtils.toString(response.getEntity()); throw new RuntimeException("requestGet remote error, url=" + uri.toString() + ", code=" + statusCode + ", error msg=" + errorMsg); response.close(); httpGet.releaseConnection();
/** * * @param response the httpresponse for processing * @param charset the charset used for getting HttpEntity * @param decode determines if the result should be decoded or not * @return HttpEntity in String representation using provided charset * @throws IOException */ public static String responseToString( HttpResponse response, Charset charset, boolean decode ) throws IOException { HttpEntity entity = response.getEntity(); String result = EntityUtils.toString( entity, charset ); EntityUtils.consume( entity ); if ( decode ) { result = URLDecoder.decode( result, StandardCharsets.UTF_8.name() ); } return result; }
private boolean httpGet(StringBuilder postAddr) { boolean ret = false; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { HttpGet request = new HttpGet(postAddr.toString()); response = httpClient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { LOG.info(EntityUtils.toString(entity)); } EntityUtils.consume(entity); ret = true; } catch (Exception e) { LOG.error("Exception when sending http request to ali monitor", e); } finally { try { if (response != null) response.close(); httpClient.close(); } catch (Exception e) { LOG.error("Exception when closing httpclient", e); } } return ret; }
private String getHttpResponse(String fullUrl) throws IOException { HttpUriRequest req = new HttpGet(fullUrl); for (int numTries = 0;; numTries++) { try (CloseableHttpResponse response = this.httpClient.execute(req)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 || statusCode >= 300) { throw new IOException( String.format("status code: %d, reason: %s", statusCode, response.getStatusLine().getReasonPhrase())); } return EntityUtils.toString(response.getEntity()); } catch (IOException e) { String errMsg = "Unable to get or parse HTTP response for " + fullUrl; if (numTries >= this.maxNumTries) { throw new IOException (errMsg, e); } long backOffSec = (numTries + 1) * 2; log.error(errMsg + ", will retry in " + backOffSec + " sec", e); try { Thread.sleep(TimeUnit.SECONDS.toMillis(backOffSec)); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } } } } }
HttpPost request = new HttpPost( new URIBuilder() .setScheme("https") .build() ); request.setEntity(new StringEntity("an_example_body")); HttpResponse response = httpClient.execute(request); assertEquals(HttpStatusCode.OK_200.code(), response.getStatusLine().getStatusCode()); assertEquals("an_example_body", new String(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8));
String host = serversList.get(); String url = host + "/" + BULK_ENDPOINT; HttpPost httpRequest = new HttpPost(url); httpRequest.setEntity(new StringEntity(entity)); response = httpClient.execute(httpRequest); statusCode = response.getStatusLine().getStatusCode(); logger.info("Status code from elasticsearch: " + statusCode); if (response.getEntity() != null) { logger.debug("Status message from elasticsearch: " + EntityUtils.toString(response.getEntity(), "UTF-8")); if (response.getEntity() != null) { throw new EventDeliveryException(EntityUtils.toString(response.getEntity(), "UTF-8")); } else { throw new EventDeliveryException("Elasticsearch status code was: " + statusCode);
HttpClient httpClient = new DefaultHttpClient(); httpPost = new HttpPost(url); httpPost.setHeader("Content-type", "application/json; charset=utf-8"); httpPost.setEntity(httpEntity); HttpResponse httpResponse = httpClient.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity resEntity = httpResponse.getEntity(); if (resEntity != null) { String result = EntityUtils.toString(resEntity, Charset.forName("utf-8")); return JSONObject.parseObject(result, BaseResult.class);
.setSocketTimeout(timeout) .build(); httpPost = new HttpPost(uri); List<NameValuePair> parameters = Lists.newArrayList(); for (String key : params.keySet()) { parameters.add(nameValuePair); httpPost.setEntity(new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8"))); HttpClientContext context = HttpClientContext.create(); context.setRequestConfig(config); context.setCookieStore(cookieStore); response = httpclient.execute(httpPost, context); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { long end = System.currentTimeMillis(); long cost = end - start; printCurlRequest(url, cookieStore, params, cost); return EntityUtils.toString(response.getEntity()); } else { long end = System.currentTimeMillis(); String curlRequest = getCurlRequest(url, cookieStore, params, cost); throw new RuntimeException("requestPost remote error, request : " + curlRequest + ", statusCode=" + statusCode + ";" + EntityUtils.toString(response.getEntity())); httpPost.releaseConnection();
/** * Signal the broker that the given high-priority task is completed, providing a result. */ public void finishPriorityTask(AnalystClusterRequest clusterRequest, Object result) { String url = BROKER_BASE_URL + String.format("/complete/priority/%s", clusterRequest.taskId); HttpPost httpPost = new HttpPost(url); try { // TODO reveal any errors etc. that occurred on the worker. // Really this should probably be done with an InputStreamEntity and a JSON writer thread. byte[] serializedResult = objectMapper.writeValueAsBytes(result); httpPost.setEntity(new ByteArrayEntity(serializedResult)); HttpResponse response = httpClient.execute(httpPost); // Signal the http client library that we're done with this response object, allowing connection reuse. EntityUtils.consumeQuietly(response.getEntity()); if (response.getStatusLine().getStatusCode() == 200) { LOG.info("Successfully marked task {} as completed.", clusterRequest.taskId); } else if (response.getStatusLine().getStatusCode() == 404) { LOG.info("Task {} was not marked as completed because it doesn't exist.", clusterRequest.taskId); } else { LOG.info("Failed to mark task {} as completed, ({}).", clusterRequest.taskId, response.getStatusLine()); } } catch (Exception e) { LOG.warn("Failed to mark task {} as completed.", clusterRequest.taskId, e); } }
HttpPost request = new HttpPost( new URIBuilder() .setScheme("http") .build() ); request.addHeader(setCookieOneHeader); request.addHeader(setCookieTwoHeader); request.addHeader(cookieOneHeader); request.addHeader(cookieTwoHeader); request.setEntity(new StringEntity("an_example_body")); HttpResponse response = httpClient.execute(request); assertEquals(HttpStatusCode.OK_200.code(), response.getStatusLine().getStatusCode()); assertThat(response.getHeaders("Set-Cookie").length, is(2)); assertThat(response.getHeaders("Set-Cookie")[0].getValue(), is(setCookieOneHeader.getValue())); assertThat(response.getHeaders("Set-Cookie")[1].getValue(), is(setCookieTwoHeader.getValue())); assertEquals("an_example_body", new String(EntityUtils.toByteArray(response.getEntity()), UTF_8));
try { method = new HttpGet(applicationRepositoryUrl + "registry.xml"); HttpResponse response = client.execute(method); int code = response.getStatusLine().getStatusCode(); log.debug("HTTP response code: {}", code); if (code == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { String responseText = EntityUtils.toString(entity); log.debug("Response: {}", responseText); log.error("Http error connecting to {}", applicationRepositoryUrl, he); if (method != null) { method.abort(); method.abort();
try { encodedUri = new URI(url); httpGet = new HttpGet(encodedUri); httpGet = new HttpGet(encodedUrl); e.printStackTrace(); httpClient.getParams().setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, 4000); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 4000); try { HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse != null) { int httpCode = httpResponse.getStatusLine().getStatusCode(); if (httpCode == HttpStatus.SC_OK) { HttpEntity entity = httpResponse.getEntity(); Header header = httpResponse .getFirstHeader("Content-Encoding"); if (header != null && header.getValue().equals("gzip")) { Log.d(TAG_LISTLOGIC, "数据已做gzip压缩..."); byte[] resultstream = EntityUtils.toByteArray(entity); resultstream = unGZip(resultstream); return new String(resultstream, "UTF-8"); httpGet.abort();
url = BROKER_BASE_URL + "/dequeue/" + graphId; HttpPost httpPost = new HttpPost(url); httpPost.setHeader(new BasicHeader(WORKER_ID_HEADER, machineId)); HttpResponse response = null; try { response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (entity == null) { return null; if (response.getStatusLine().getStatusCode() != 200) { EntityUtils.consumeQuietly(entity); return null;
/** * Tell the broker that the given message has been successfully processed by a worker (HTTP DELETE). */ public void deleteRequest(AnalystClusterRequest clusterRequest) { String url = BROKER_BASE_URL + String.format("/tasks/%s", clusterRequest.taskId); HttpDelete httpDelete = new HttpDelete(url); try { HttpResponse response = httpClient.execute(httpDelete); // Signal the http client library that we're done with this response object, allowing connection reuse. EntityUtils.consumeQuietly(response.getEntity()); if (response.getStatusLine().getStatusCode() == 200) { LOG.info("Successfully deleted task {}.", clusterRequest.taskId); } else { LOG.info("Failed to delete task {} ({}).", clusterRequest.taskId, response.getStatusLine()); } } catch (Exception e) { LOG.warn("Failed to delete task {}", clusterRequest.taskId, e); } }
.setSocketTimeout(timeout) .build(); getMethod.setConfig(requestConfig); HttpResponse response = httpClient.execute(getMethod); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpResponseStatus.OK.code() && statusCode != HttpResponseStatus.PARTIAL_CONTENT.code()) { String result = EntityUtils.toString(response.getEntity()); throw new RuntimeException("return error !" + response.getStatusLine().getReasonPhrase() + ", " + result);
try { method = new HttpGet(applicationRepositoryUrl + applicationWarName); method.addHeader("Accept-Encoding", "identity"); HttpResponse response = client.execute(method); int code = response.getStatusLine().getStatusCode(); log.debug("HTTP response code: {}", code); if (code == 200) { HttpEntity entity = response.getEntity(); if (entity != null) { byte[] buf = EntityUtils.toByteArray(entity); fos.write(buf); fos.flush(); log.error("Http error connecting to {}", applicationRepositoryUrl, he); if (method != null) { method.abort();
vHttpMethod.setEntity( requestEntity ); HttpResponse httpResponse = cachedHttpClient.execute( vHttpMethod ); int responseCode = httpResponse.getStatusLine().getStatusCode(); if ( responseCode == HttpStatus.SC_MOVED_PERMANENTLY ) { String newLocation = getLocationFrom( vHttpMethod ); vHttpMethod = getHttpMethod( newLocation ); vHttpMethod.setEntity( requestEntity ); httpResponse = cachedHttpClient.execute( vHttpMethod ); responseCode = httpResponse.getStatusLine().getStatusCode(); httpEntity = httpResponse.getEntity(); ContentType contentType = ContentType.getOrDefault( httpEntity ); charSet = contentType.getCharset(); throw new KettleStepException( BaseMessages.getString( PKG, "WebServices.ERROR0001.ServerError", Integer.toString( responseCode ), Const.NVL( new String( EntityUtils.toString( httpEntity, charSet.toString() ) ), "" ), cachedURLService ) ); vHttpMethod.releaseConnection();
HttpPost httpPost = new HttpPost(url); httpPost.addHeader("charset", StandardCharsets.UTF_8.name()); httpPost.setConfig(requestConfig); httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(request), ContentType.APPLICATION_JSON)); try (CloseableHttpResponse response = httpclient.execute(httpPost, options.getHttpContext())) { HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); if (response.getStatusLine().getStatusCode() >= 500) { BotLogger.warn(LOGTAG, responseContent); synchronized (lock) {