public ResponseWrap(CloseableHttpClient httpClient, HttpRequestBase request, CloseableHttpResponse response, HttpClientContext context, ObjectMapper _mapper) { this.response = response; this.httpClient = httpClient; this.request = request; this.context = context; mapper = _mapper; try { HttpEntity entity = response.getEntity(); if (entity != null) { this.entity = new BufferedHttpEntity(entity); } else { this.entity = new BasicHttpEntity(); } EntityUtils.consumeQuietly(entity); this.response.close(); } catch (IOException e) { logger.warn(e.getMessage()); } }
@Override protected final <T extends Serializable, Method extends BotApiMethod<T>> T sendApiMethod(Method method) throws TelegramApiException { method.validate(); String responseContent; try { String url = getBaseUrl() + method.getMethod(); HttpPost httppost = new HttpPost(url); httppost.setConfig(requestConfig); httppost.addHeader("charset", StandardCharsets.UTF_8.name()); httppost.setEntity(new StringEntity(objectMapper.writeValueAsString(method), ContentType.APPLICATION_JSON)); try (CloseableHttpResponse response = httpclient.execute(httppost)) { HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); } } catch (IOException e) { throw new TelegramApiException("Unable to execute " + method.getMethod() + " method", e); } return method.deserializeResponse(responseContent); }
private Serializable sendApiMethod(BotApiMethod method) throws TelegramApiException { String responseContent; try { CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); String url = getBaseUrl() + method.getPath(); HttpPost httppost = new HttpPost(url); httppost.addHeader("charset", StandardCharsets.UTF_8.name()); httppost.setEntity(new StringEntity(method.toJson().toString(), ContentType.APPLICATION_JSON)); CloseableHttpResponse response = httpclient.execute(httppost); HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); } catch (IOException e) { throw new TelegramApiException("Unable to execute " + method.getPath() + " method", e); } JSONObject jsonObject = new JSONObject(responseContent); if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { throw new TelegramApiException("Error at " + method.getPath(), jsonObject.getString("description")); } return method.deserializeResponse(jsonObject); }
private void download(String url, Handler<AsyncResult<Object>> handler) { vertx.executeBlocking(future -> { HttpGet httpGet = new HttpGet(rootOPDS + url); try { CloseableHttpResponse response = httpclient.execute(httpGet, context); if (response.getStatusLine().getStatusCode() == 200) { String fileName = fileNameParser.parse(url); HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); File book = File.createTempFile("flibot_" + Long.toHexString(System.currentTimeMillis()), null); buf.writeTo(new FileOutputStream(book)); final SendDocument sendDocument = new SendDocument(); sendDocument.setNewDocument(fileName, new FileInputStream(book)); sendDocument.setCaption("book"); future.complete(sendDocument); } } catch (Exception e) { log.warn(e, e); future.fail(e); } }, res -> { handler.handle(res); }); }
@Override public <T extends TelegraphObject> T execute(TelegraphMethod<T> method) throws TelegraphException { String responseContent; try { String url = TelegraphConstants.BASE_URL + method.getUrlPath(); HttpPost httppost = new HttpPost(url); httppost.setConfig(requestConfig); httppost.addHeader("charset", StandardCharsets.UTF_8.name()); httppost.addHeader("Content-Type", "application/json"); httppost.setEntity(new StringEntity(objectMapper.writeValueAsString(method), ContentType.APPLICATION_JSON)); try (CloseableHttpResponse response = httpclient.execute(httppost)) { HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); } } catch (IOException e) { throw new TelegraphRequestException("Unable to execute " + method.getUrlPath() + " method", e); } return method.deserializeResponse(responseContent); }
public static ByteArrayBuffer ʻ(String paramString) { HttpGet localHttpGet = new HttpGet(paramString); DefaultHttpClient localDefaultHttpClient = ˊ(); BufferedHttpEntity localBufferedHttpEntity = new BufferedHttpEntity(localDefaultHttpClient.execute(localHttpGet).getEntity()); BufferedInputStream localBufferedInputStream = new BufferedInputStream(localBufferedHttpEntity.getContent()); ByteArrayBuffer localByteArrayBuffer = new ByteArrayBuffer(50); while (true) { int i = localBufferedInputStream.read(); if (i == -1) break; localByteArrayBuffer.append((byte)i); } localBufferedInputStream.close(); localBufferedHttpEntity.consumeContent(); localDefaultHttpClient.getConnectionManager().shutdown(); return localByteArrayBuffer; }
public static void log(HttpRequest req, BufferedHttpEntity entity) { if (log_level > 1) { System.out.println("----------------------"); System.out.println(" HTTP Request"); System.out.println("----------------------"); System.out.println(req.getRequestLine().toString()); if (log_level > 2) { System.out.println("Headers:"); System.out.println("--------"); Header[] hdrs = req.getAllHeaders(); for (int i = 0; i < hdrs.length; ++i) { System.out.println(hdrs[i].getName() + ": " + hdrs[i].getValue()); } if (entity != null) { try { System.out.println("Entity:"); System.out.println("-------"); System.out.println(EntityUtils.toString(entity)); } catch (IOException e) { e.printStackTrace(); } } } System.out.println(""); } }
public static void log(HttpResponse response, BufferedHttpEntity entity) { if (log_level > 1) { System.out.println("------------------------"); System.out.println(" HTTP Response:"); System.out.println("------------------------"); System.out.println("Status: " + response.getStatusLine()); if (log_level > 2) { System.out.println("Headers:"); System.out.println("--------"); Header[] hdrs = response.getAllHeaders(); for (int i = 0; i < hdrs.length; ++i) { System.out.println(hdrs[i].getName() + ": " + hdrs[i].getValue()); } if (entity != null) { try { System.out.println("Entity:"); System.out.println("-------"); System.out.println(EntityUtils.toString(entity)); } catch (IOException e) { e.printStackTrace(); } } } System.out.println(""); } }
/** * <p>Test for a {@link Request} with a <b>buffered</b> entity.</p> * * @since 1.3.0 */ @Test public final void testBufferedHttpEntity() throws ParseException, IOException { String subpath = "/bufferedhttpentity"; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classLoader.getResourceAsStream("LICENSE.txt"); InputStream parallelInputStream = classLoader.getResourceAsStream("LICENSE.txt"); BasicHttpEntity bhe = new BasicHttpEntity(); bhe.setContent(parallelInputStream); stubFor(put(urlEqualTo(subpath)) .willReturn(aResponse() .withStatus(200))); requestEndpoint.bufferedHttpEntity(inputStream); verify(putRequestedFor(urlEqualTo(subpath)) .withRequestBody(equalTo(EntityUtils.toString(new BufferedHttpEntity(bhe))))); }
/** * <p>Test for a {@link Request} with a <b>buffered</b> entity.</p> * * @since 1.3.0 */ @Test public final void testBufferedHttpEntity() throws ParseException, IOException { Robolectric.getFakeHttpLayer().interceptHttpRequests(false); String subpath = "/bufferedhttpentity"; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classLoader.getResourceAsStream("LICENSE.txt"); InputStream parallelInputStream = classLoader.getResourceAsStream("LICENSE.txt"); BasicHttpEntity bhe = new BasicHttpEntity(); bhe.setContent(parallelInputStream); stubFor(put(urlEqualTo(subpath)) .willReturn(aResponse() .withStatus(200))); requestEndpoint.bufferedHttpEntity(inputStream); verify(putRequestedFor(urlEqualTo(subpath)) .withRequestBody(equalTo(EntityUtils.toString(new BufferedHttpEntity(bhe))))); }
private byte[] serializeContent(HttpRequest request) { if (!(request instanceof HttpEntityEnclosingRequest)) { return new byte[]{}; } final HttpEntityEnclosingRequest entityWithRequest = (HttpEntityEnclosingRequest) request; HttpEntity entity = entityWithRequest.getEntity(); if (entity == null) { return new byte[]{}; } try { // Buffer non-repeatable entities if (!entity.isRepeatable()) { entityWithRequest.setEntity(new BufferedHttpEntity(entity)); } return EntityUtils.toByteArray(entityWithRequest.getEntity()); } catch (IOException e) { throw new RuntimeException(e); } }
@Override protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException { HttpGet httpRequest = new HttpGet(imageUri); HttpResponse response = httpClient.execute(httpRequest); HttpEntity entity = response.getEntity(); BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); return bufHttpEntity.getContent(); }
protected void sendResponseMessage(HttpResponse response) { Throwable e; StatusLine status = response.getStatusLine(); String responseBody = null; try { HttpEntity temp = response.getEntity(); if (temp != null) { HttpEntity entity = new BufferedHttpEntity(temp); try { responseBody = EntityUtils.toString(entity, "UTF-8"); } catch (IOException e2) { e = e2; HttpEntity httpEntity = entity; sendFailureMessage(e, null); if (status.getStatusCode() >= 300) { sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); } else { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody); } } } } catch (IOException e3) { e = e3; sendFailureMessage(e, null); if (status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody); } else { sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); } } if (status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody); } else { sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); } }
/** * Utility function for creating a new BufferedEntity and wrapping any errors * as a SdkClientException. * * @param entity The HTTP entity to wrap with a buffered HTTP entity. * @return A new BufferedHttpEntity wrapping the specified entity. */ public static HttpEntity newBufferedHttpEntity(HttpEntity entity) { try { return new BufferedHttpEntity(entity); } catch (IOException e) { throw new UncheckedIOException("Unable to create HTTP entity: " + e.getMessage(), e); } }
@Override public void afterDoCap(InvokeChainContext context, Object[] args) { if (UAVServer.instance().isExistSupportor("com.creditease.uav.apm.supporters.SlowOperSupporter")) { Span span = (Span) context.get(InvokeChainConstants.PARAM_SPAN_KEY); SlowOperContext slowOperContext = new SlowOperContext(); if (Throwable.class.isAssignableFrom(args[0].getClass())) { Throwable e = (Throwable) args[0]; slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_EXCEPTION, e.toString()); } else { HttpResponse response = (HttpResponse) args[0]; slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_HEADER, getResponHeaders(response)); HttpEntity entity = response.getEntity(); // 由于存在读取失败和无法缓存的大entity会使套壳失败,故此处添加如下判断 if (BufferedHttpEntity.class.isAssignableFrom(entity.getClass())) { Header header = entity.getContentEncoding(); String encoding = header == null ? "utf-8" : header.getValue(); slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_BODY, getHttpEntityContent(entity, encoding)); } else { slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_BODY, "HttpEntityWrapper failed! Maybe HTTP entity too large to be buffered in memory"); } } Object params[] = { span, slowOperContext }; UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.SlowOperSupporter", "runCap", span.getEndpointInfo().split(",")[0], InvokeChainConstants.CapturePhase.DOCAP, context, params); } }
private void sendApiMethodAsync(BotApiMethod method, SentCallback callback) { exe.submit(new Runnable() { @Override public void run() { try { CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); String url = getBaseUrl() + method.getPath(); HttpPost httppost = new HttpPost(url); httppost.addHeader("charset", StandardCharsets.UTF_8.name()); httppost.setEntity(new StringEntity(method.toJson().toString(), ContentType.APPLICATION_JSON)); CloseableHttpResponse response = httpclient.execute(httppost); HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8); JSONObject jsonObject = new JSONObject(responseContent); if (!jsonObject.getBoolean(Constants.RESPONSEFIELDOK)) { callback.onError(method, jsonObject); } callback.onResult(method, jsonObject); } catch (IOException e) { callback.onException(method, e); } } }); }
protected HttpResponse execute(final HttpClient client, final HttpRequestBase request) throws Exception { HttpContext context = new BasicHttpContext(); HttpResponse response = requestChain.execute(request, context); if (context.getAttribute("Location")!=null) response.setHeader(MECHANIZE_LOCATION, (String) context.getAttribute("Location")); response.setEntity(new BufferedHttpEntity(response.getEntity())); return response; }
private String sendHttpPostRequest(HttpPost httppost) throws IOException { try (CloseableHttpResponse response = httpclient.execute(httppost)) { HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); return EntityUtils.toString(buf, StandardCharsets.UTF_8); } }
public HttpResponse doExecute(HttpUriRequest method) throws Exception { CloseableHttpClient client = HttpClientBuilder.create().build(); try { HttpResponse response = client.execute(method); response.setEntity(new BufferedHttpEntity(response.getEntity())); return response; } finally { client.close(); } }
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request; HttpEntity requestEntity = enclosingRequest.getEntity(); enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity)); } }
private String getSideBar(String subreddit) throws IOException { //noinspection deprecation @SuppressWarnings("deprecation") HttpClient client = new DefaultHttpClient(); URL url = null; try { url = new URL("http://www.reddit.com/r/" + subreddit + "/about/edit.json"); HttpGet httpGet = new HttpGet(String.valueOf(url)); //noinspection deprecation,deprecation client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("User-Agent: LGG Bot (by /u/amdphenom")); httpGet.addHeader("Cookie", "reddit_session=" + user.getCookie()); httpGet.addHeader("uh", user.getModhash()); HttpResponse response = client.execute(httpGet); HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); InputStream is = buf.getContent(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); StringBuilder total = new StringBuilder(); String line; while ((line = r.readLine()) != null) { total.append(line); } System.out.println(total.toString()); return total.toString(); } catch (Exception e) { e.printStackTrace(); System.err.println("Sidebar download failed"); } return ("fail"); }
/** * Utility function for creating a new BufferedEntity and wrapping any errors * as a RestException. * * @param entity The HTTP entity to wrap with a buffered HTTP entity. * @return A new BufferedHttpEntity wrapping the specified entity. */ private HttpEntity newBufferedHttpEntity(HttpEntity entity) { try { return new BufferedHttpEntity(entity); } catch (IOException e) { throw new RestException("Unable to create HTTP entity: " + e.getMessage(), e); } }
@Override public void saveFile(String path, InputStream input) { try { saveFile(path, new BufferedHttpEntity(new InputStreamEntity(input))); } catch (IOException e) { throw new RuntimeException("Could not create buffered http entity", e); } }
public List<RaeResult> getResults(String query) { List<RaeResult> results = new ArrayList<>(); String completeURL; try { completeURL = BASEURL + SEARCHEXACTURL + URLEncoder.encode(query, "UTF-8"); CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); HttpGet request = new HttpGet(completeURL); CloseableHttpResponse response = client.execute(request); HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); String responseString = EntityUtils.toString(buf, "UTF-8"); Document document = Jsoup.parse(responseString); Element article = document.getElementsByTag("article").first(); String articleId = null; if (article != null) { articleId = article.attributes().get("id"); } Elements elements = document.select(".j"); if (elements.isEmpty()) { results = getResultsWordSearch(query); } else { results = getResultsFromExactMatch(elements, query, articleId); } } catch (IOException e) { BotLogger.error(LOGTAG, e); } return results; }
private List<RaeResult> getResultsWordSearch(String query) { List<RaeResult> results = new ArrayList<>(); String completeURL; try { completeURL = BASEURL + SEARCHWORDURL + URLEncoder.encode(query, "UTF-8"); CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); HttpGet request = new HttpGet(completeURL); CloseableHttpResponse response = client.execute(request); HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); String responseString = EntityUtils.toString(buf, "UTF-8"); Document document = Jsoup.parse(responseString); Element list = document.select("body div ul").first(); if (list != null) { Elements links = list.getElementsByTag("a"); if (!links.isEmpty()) { for (Element link : links) { List<RaeResult> partialResults = fetchWord(URLEncoder.encode(link.attributes().get("href"), "UTF-8"), link.text()); if (!partialResults.isEmpty()) { results.addAll(partialResults); } } } } } catch (IOException e) { BotLogger.error(LOGTAG, e); } return results; }
private List<RaeResult> fetchWord(String link, String word) { List<RaeResult> results = new ArrayList<>(); String completeURL; try { completeURL = BASEURL + link; CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); HttpGet request = new HttpGet(completeURL); CloseableHttpResponse response = client.execute(request); HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); String responseString = EntityUtils.toString(buf, "UTF-8"); Document document = Jsoup.parse(responseString); Element article = document.getElementsByTag("article").first(); String articleId = null; if (article != null) { articleId = article.attributes().get("id"); } Elements elements = document.select(".j"); if (!elements.isEmpty()) { results = getResultsFromExactMatch(elements, word, articleId); } } catch (IOException e) { BotLogger.error(LOGTAG, e); } return results; }
public static Bitmap downloadImage(String url) { HttpParams hparams = new BasicHttpParams(); /** * You can also add timeouts to the settings menu in a real project */ HttpConnectionParams.setConnectionTimeout(hparams, 10000); HttpConnectionParams.setSoTimeout(hparams, 10000); HttpGet get = new HttpGet(url); DefaultHttpClient client; try { if (doAcceptAllSSL) client = (DefaultHttpClient) SSLErrorPreventer .setAcceptAllSSL(new DefaultHttpClient(hparams)); else client = new DefaultHttpClient(hparams); HttpResponse response = null; if (doUseCookie) { CookieStore store = client.getCookieStore(); HttpContext ctx = new BasicHttpContext(); store.addCookie(Utils.sessionCookie); ctx.setAttribute(ClientContext.COOKIE_STORE, store); } response = client.execute(get); network_response = response.getStatusLine().toString(); MainActivity.tmpResponseForUIDownload = network_response; HttpEntity responseEntity = response.getEntity(); BufferedHttpEntity httpEntity = new BufferedHttpEntity( responseEntity); InputStream imageStream = httpEntity.getContent(); return BitmapFactory.decodeStream(imageStream); } catch (Exception ex) { ex.printStackTrace(); return null; } }
public RestResponse putRaw(String endPoint, RawInput stream) throws IOException { Preconditions.checkNotNull(stream); Request put = Request.Put(getUrl(endPoint)); put.addHeader(new BasicHeader("Content-Type", stream.getContentType())); put.body( new BufferedHttpEntity( new InputStreamEntity(stream.getInputStream(), stream.getContentLength()))); return execute(put); }