List of usage examples for org.apache.http.entity BufferedHttpEntity BufferedHttpEntity
public BufferedHttpEntity(HttpEntity httpEntity) throws IOException
From source file:markson.visuals.sitapp.settingActivity.java
public static String getCancelNum() { String classNum = "0"; DefaultHttpClient client = new DefaultHttpClient(); try {/*w w w . j a va 2 s .com*/ HttpGet httpGet = new HttpGet("http://marksonvisuals.com/sitapp/ccnum.php"); 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 + "\n"); } classNum = total.toString().replaceAll("[^0-9]", ""); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return classNum; }
From source file:de.mojadev.ohmmarks.virtuohm.VirtuOhmHTTPHandler.java
private String getResponseText(HttpResponse response) throws IllegalStateException, IOException { BufferedHttpEntity responseEntity = new BufferedHttpEntity(response.getEntity()); int contentLength = (int) responseEntity.getContentLength(); InputStream stream = responseEntity.getContent(); byte buffer[] = new byte[contentLength]; stream.read(buffer, 0, contentLength); return new String(buffer); }
From source file:pt.lunacloud.http.HttpRequestFactory.java
/** * Utility function for creating a new BufferedEntity and wrapping any errors * as an AmazonClientException./*from w w w . j a v a 2 s . c om*/ * * @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 LunacloudClientException("Unable to create HTTP entity: " + e.getMessage(), e); } }
From source file:io.uploader.drive.drive.largefile.DriveResumableUpload.java
public long getCurrentByte() throws IOException { logger.info("Querying status of resumable upload..."); CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; long lastbyte = -1; try {/* w ww . j a va2 s . c o m*/ httpclient = getHttpClient(); BasicHttpRequest httpreq = new BasicHttpRequest("PUT", location); httpreq.addHeader("Authorization", auth.getAuthHeader()); httpreq.addHeader("Content-Length", "0"); httpreq.addHeader("Content-Range", "bytes */" + getFileSizeString()); //logger.info(httpreq.toString()); response = httpclient.execute(URIUtils.extractHost(uri), httpreq); @SuppressWarnings("unused") BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity()); EntityUtils.consume(response.getEntity()); if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201) { lastbyte = fileSize; } if (response.getStatusLine().getStatusCode() == 308) { if (response.getHeaders("Range").length > 0) { String range = response.getHeaders("Range")[0].getValue(); String[] parts = range.split("-"); lastbyte = Long.parseLong(parts[1]) + 1; } else { // nothing uploaded, but file is there to start upload! lastbyte = 0; } } return lastbyte; } finally { if (response != null) { response.close(); } if (httpclient != null) { httpclient.close(); } } }
From source file:com.netscape.certsrv.client.PKIConnection.java
public void storeRequest(File file, HttpRequest request) throws IOException { try (PrintStream out = new PrintStream(file)) { out.println(request.getRequestLine()); for (Header header : request.getAllHeaders()) { out.println(header.getName() + ": " + header.getValue()); }//from w w w .ja va 2s .c om out.println(); if (request instanceof EntityEnclosingRequestWrapper) { EntityEnclosingRequestWrapper wrapper = (EntityEnclosingRequestWrapper) request; HttpEntity entity = wrapper.getEntity(); if (entity == null) return; if (!entity.isRepeatable()) { BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity); wrapper.setEntity(bufferedEntity); entity = bufferedEntity; } storeEntity(out, entity); } } }
From source file:cn.ctyun.amazonaws.http.HttpRequestFactory.java
/** * Utility function for creating a new BufferedEntity and wrapping any errors * as an AmazonClientException./*from w w w .java 2s .co m*/ * * @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 AmazonClientException("Unable to create HTTP entity: " + e.getMessage(), e); } }
From source file:eu.europa.esig.dss.client.http.commons.FileCacheDataLoader.java
@Override public byte[] post(final String urlString, final byte[] content) throws DSSException { final String fileName = ResourceLoader.getNormalizedFileName(urlString); // The length for the InputStreamEntity is needed, because some receivers (on the other side) need this // information. // To determine the length, we cannot read the content-stream up to the end and re-use it afterwards. // This is because, it may not be possible to reset the stream (= go to position 0). // So, the solution is to cache temporarily the complete content data (as we do not expect much here) in a // byte-array. final byte[] digest = DSSUtils.digest(DigestAlgorithm.MD5, content); final String digestHexEncoded = DSSUtils.toHex(digest); final String cacheFileName = fileName + "." + digestHexEncoded; final File file = getCacheFile(cacheFileName); if (file.exists()) { LOG.debug("Cached file was used"); final byte[] byteArray = DSSUtils.toByteArray(file); return byteArray; } else {//from w w w . ja v a2s . c o m LOG.debug("There is no cached file!"); } final byte[] returnedBytes; if (!isNetworkProtocol(urlString)) { final String resourcePath = resourceLoader.getAbsoluteResourceFolder(urlString.trim()); final File fileResource = new File(resourcePath); returnedBytes = DSSUtils.toByteArray(fileResource); return returnedBytes; } HttpPost httpRequest = null; HttpResponse httpResponse = null; try { final URI uri = URI.create(urlString.trim()); httpRequest = new HttpPost(uri); final ByteArrayInputStream bis = new ByteArrayInputStream(content); final HttpEntity httpEntity = new InputStreamEntity(bis, content.length); final HttpEntity requestEntity = new BufferedHttpEntity(httpEntity); httpRequest.setEntity(requestEntity); if (contentType != null) { httpRequest.setHeader(CONTENT_TYPE, contentType); } httpResponse = super.getHttpResponse(httpRequest, urlString); returnedBytes = readHttpResponse(urlString, httpResponse); if (returnedBytes.length != 0) { final File cacheFile = getCacheFile(cacheFileName); DSSUtils.saveToFile(returnedBytes, cacheFile); } } catch (IOException e) { throw new DSSException(e); } finally { if (httpRequest != null) { httpRequest.releaseConnection(); } if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } return returnedBytes; }
From source file:com.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java
/** * invoke creates a socket connection, sends the request SOAP message and * then reads the response SOAP message back from the SOAP server * * @param msgContext//from w ww . j a va2s.c o m * the messsage context * * @throws AxisFault */ public void invoke(final MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke")); Request req = null; Response response = null; try { if (exec == null) { targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (targetURL.getUserInfo() != null)) { String info = targetURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else userID = info; } Credentials cred = new UsernamePasswordCredentials(userID, passwd); if (userID != null) { // if the username is in the form "user\domain" // then use NTCredentials instead. int domainIndex = userID.indexOf("\\"); if (domainIndex > 0) { String domain = userID.substring(0, domainIndex); if (userID.length() > domainIndex + 1) { String user = userID.substring(domainIndex + 1); cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain); } } } HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() { public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { URI uri = getLocationURI(request, response, context); String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) return new HttpHead(uri); else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) { HttpPost httpPost = new HttpPost(uri); httpPost.addHeader(request.getFirstHeader("Authorization")); httpPost.addHeader(request.getFirstHeader("SOAPAction")); httpPost.addHeader(request.getFirstHeader("Content-Type")); httpPost.addHeader(request.getFirstHeader("User-Agent")); httpPost.addHeader(request.getFirstHeader("SOAPAction")); if (request instanceof HttpEntityEnclosingRequest) httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity()); return httpPost; } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { throw new IllegalStateException( "Redirect called on un-redirectable http method: " + method); } } }).build(); exec = Executor.newInstance(httpClient); HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol()); exec.auth(host, cred); exec.authPreemptive(host); HttpUtils.setupProxy(exec, targetURL.toURI()); } boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) posting = webMethod.equals(HTTPConstants.HEADER_POST); } HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI()); if (posting) { req = Request.Post(targetURL.toString()); if (proxy != null) req.viaProxy(proxy); Message reqMessage = msgContext.getRequestMessage(); addContextInfo(req, msgContext, targetURL); Iterator<?> it = reqMessage.getAttachments(); if (it.hasNext()) { ByteArrayOutputStream bos = null; try { bos = new ByteArrayOutputStream(); reqMessage.writeTo(bos); req.body(new ByteArrayEntity(bos.toByteArray())); } finally { FileUtils.closeStream(bos); } } else req.body(new StringEntity(reqMessage.getSOAPPartAsString())); } else { req = Request.Get(targetURL.toString()); if (proxy != null) req.viaProxy(proxy); addContextInfo(req, msgContext, targetURL); } response = exec.execute(req); response.handleResponse(new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws IOException { HttpEntity en = response.getEntity(); InputStream in = null; try { StatusLine statusLine = response.getStatusLine(); int returnCode = statusLine.getStatusCode(); String contentType = en.getContentType().getValue(); in = new BufferedHttpEntity(en).getContent(); // String str = IOUtils.toString(in); if (returnCode > 199 && returnCode < 300) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall // through, since the range of // valid result codes is much greater } else if (contentType != null && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so // fall through } else { String statusMessage = statusLine.getReasonPhrase(); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); fault.setFaultDetailString( Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in))); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) in = new GZIPInputStream(in); else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); throw fault; } } // Transfer HTTP headers of HTTP message // to MIME headers of SOAP // message MimeHeaders mh = new MimeHeaders(); for (Header h : response.getAllHeaders()) mh.addHeader(h.getName(), h.getValue()); Message outMsg = new Message(in, false, mh); outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { log.debug("\n" + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPPartAsString()); } } finally { FileUtils.closeStream(in); } return ""; } }); } catch (Exception e) { e.printStackTrace(); log.debug(e); throw AxisFault.makeFault(e); } if (log.isDebugEnabled()) log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); }
From source file:com.twotoasters.android.horizontalimagescroller.io.ImageCacheManager.java
protected InputStream fetch(ImageUrlRequest imageUrlRequest) throws MalformedURLException, IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); ImageToLoadUrl imageToLoadUrl = imageUrlRequest.getImageToLoadUrl(); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(imageToLoadUrl.getUsername(), imageToLoadUrl.getPassword())); HttpResponse response = httpClient.execute(new HttpGet(imageToLoadUrl.getUrl())); int statusCode = response.getStatusLine().getStatusCode(); String reason = response.getStatusLine().getReasonPhrase(); if (statusCode > 299) { throw new HttpResponseException(statusCode, reason); }// ww w.j a va 2s . com BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity()); return entity.getContent(); }
From source file:be.cytomine.client.HttpClient.java
public int put(byte[] data) throws IOException { log.debug("Put " + URL.getPath()); HttpPut httpPut = new HttpPut(URL.getPath()); if (isAuthByPrivateKey) { httpPut.setHeaders(headersArray); }//from w w w.j a v a 2 s .c o m log.debug("Put send :" + data.length); InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(data), data.length); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(false); BufferedHttpEntity myEntity = null; try { myEntity = new BufferedHttpEntity(reqEntity); } catch (IOException e) { // TODO Auto-generated catch block log.error(e); } httpPut.setEntity(myEntity); response = client.execute(targetHost, httpPut, localcontext); return response.getStatusLine().getStatusCode(); }