List of usage examples for org.apache.http.util EntityUtils toByteArray
public static byte[] toByteArray(HttpEntity httpEntity) throws IOException
From source file:com.example.wechatsample.library.http.BinaryHttpResponseHandler.java
void sendResponseMessage(HttpResponse response) { StatusLine status = response.getStatusLine(); Header[] contentTypeHeaders = response.getHeaders("Content-Type"); byte[] responseBody = null; if (contentTypeHeaders.length != 1) { // malformed/ambiguous HTTP Header, ABORT! sendFailureMessage(new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"), responseBody); return;//ww w.j a v a2s. c o m } Header contentTypeHeader = contentTypeHeaders[0]; boolean foundAllowedContentType = false; for (String anAllowedContentType : mAllowedContentTypes) { if (anAllowedContentType.equals(contentTypeHeader.getValue())) { foundAllowedContentType = true; } } if (!foundAllowedContentType) { // Content-Type not in allowed list, ABORT! sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"), responseBody); return; } try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if (temp != null) { entity = new BufferedHttpEntity(temp); } responseBody = EntityUtils.toByteArray(entity); } catch (IOException e) { sendFailureMessage(e, (byte[]) null); } if (status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody); } else { sendSuccessMessage(status.getStatusCode(), responseBody); } }
From source file:cx.fbn.nevernote.threads.ENThumbnailRunner.java
private synchronized QByteArray getENThumbnailData(String guid) { // ?Evernote??? String shardId = user.getShardId(); if (shardId == null || shardId.equals("")) { return null; }// w ww.ja v a2 s .com OAuthTokenizer tokenizer = new OAuthTokenizer(); AESEncrypter aes = new AESEncrypter(); try { aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("oauthkey.txt"))); } catch (FileNotFoundException e) { logger.log(logger.HIGH, "Evernote???FileNotFoundException"); e.printStackTrace(); return null; } String authString = aes.getString(); String oauthToken = new String(); if (!authString.equals("")) { tokenizer.tokenize(authString); oauthToken = tokenizer.oauth_token; } HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost( "https://" + serverUrl + "/shard/" + user.getShardId() + "/thm/note/" + guid + ".png"); httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); httpPost.setHeader("Host", getServerUrl()); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("auth", oauthToken)); nameValuePairs.add(new BasicNameValuePair("size", "80")); QByteArray data = new QByteArray(); try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Web????? HttpResponse response = null; response = httpClient.execute(httpPost); byte[] bytes = EntityUtils.toByteArray(response.getEntity()); data = new QByteArray(bytes); } catch (UnsupportedEncodingException e) { logger.log(logger.HIGH, "Evernote???UnsupportedEncodingException"); e.printStackTrace(); return null; } catch (ClientProtocolException e) { logger.log(logger.HIGH, "Evernote???ClientProtocolException"); e.printStackTrace(); return null; } catch (IOException e) { logger.log(logger.HIGH, "Evernote???IOException"); e.printStackTrace(); return null; } finally { httpClient.getConnectionManager().shutdown(); } return data; }
From source file:com.kkbox.toolkit.internal.api.APIRequest.java
public void addGZIPPostParam(String key, String value) { try {/*from w ww .j av a 2 s . c o m*/ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add((new BasicNameValuePair(key, value))); GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream); gZIPOutputStream.write(EntityUtils.toByteArray(new UrlEncodedFormEntity(postParams, HTTP.UTF_8))); gZIPOutputStream.close(); byte[] byteDataForGZIP = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.close(); gzipStreamEntity = new InputStreamEntity(new ByteArrayInputStream(byteDataForGZIP), byteDataForGZIP.length); gzipStreamEntity.setContentType("application/x-www-form-urlencoded"); gzipStreamEntity.setContentEncoding("gzip"); } catch (Exception e) { } }
From source file:org.nextlets.erc.defaults.http.ERCHttpInvokerImpl.java
protected byte[] getResponseBody(ERCConfiguration configuration, HttpResponse httpResp) { log.debug("Getting response body..."); HttpEntity entity = httpResp.getEntity(); byte[] responseBody = new byte[0]; try {//from w w w. j a va 2 s. com responseBody = (entity == null ? responseBody : EntityUtils.toByteArray(entity)); } catch (ParseException ex) { throw new ERCClientException(ex); } catch (IOException ex) { throw new ERCClientException(ex); } log.debug("Response body length: ", responseBody.length); return responseBody; }
From source file:com.fastandroid.lib.http.AsyncHttpClient.BinaryHttpResponseHandler.java
@Override protected void sendResponseMessage(HttpResponse response) { StatusLine status = response.getStatusLine(); Header[] contentTypeHeaders = response.getHeaders("Content-Type"); byte[] responseBody = null; if (contentTypeHeaders.length != 1) { // malformed/ambiguous HTTP Header, ABORT! sendFailureMessage(new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"), responseBody); return;//from w w w .j ava 2 s.c o m } Header contentTypeHeader = contentTypeHeaders[0]; boolean foundAllowedContentType = false; for (String anAllowedContentType : mAllowedContentTypes) { if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) { foundAllowedContentType = true; } } if (!foundAllowedContentType) { // Content-Type not in allowed list, ABORT! sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"), responseBody); return; } try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if (temp != null) { entity = new BufferedHttpEntity(temp); } responseBody = EntityUtils.toByteArray(entity); } catch (IOException e) { sendFailureMessage(e, (byte[]) null); } if (status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody); } else { sendSuccessMessage(status.getStatusCode(), responseBody); } }
From source file:org.opcfoundation.ua.transport.https.HttpsServerPendingRequest.java
@Override public void run() { // This code is ran in a worker thread. workerThread = Thread.currentThread(); // 0. Check content Length from the header Header header = httpRequest.getFirstHeader("Content-Length"); if (header != null) { String len = header.getValue().trim(); if (!len.isEmpty()) { try { long contentLength = Long.valueOf(len); long maxMessageSize = endpoint.endpointConfiguration.getMaxMessageSize(); // 1. Reject content if (maxMessageSize != 0 && contentLength > maxMessageSize) { sendError(500, StatusCodes.Bad_RequestTooLarge, "No request message"); return; }//w w w.j av a2 s.c om } catch (NumberFormatException nfe) { } } } // 1. Decode message try { byte[] data; if (httpRequest instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) httpRequest; requestEntity = entityEnclosingRequest.getEntity(); // Check content length from the entity ( chucked case ) long contentLength = requestEntity.getContentLength(); long maxMessageSize = endpoint.endpointConfiguration.getMaxMessageSize(); // 1. Reject content if (maxMessageSize != 0 && contentLength > maxMessageSize) { sendError(500, StatusCodes.Bad_RequestTooLarge, "No request message"); return; } data = EntityUtils.toByteArray(requestEntity); } else { sendError(500, StatusCodes.Bad_RequestTypeInvalid, "No request message"); return; } BinaryDecoder dec = new BinaryDecoder(data); dec.setEncoderContext(endpoint.getEncoderContext()); super.request = dec.getMessage(); logger.trace("request={}", super.request); logger.debug("request={}", super.request.getClass().getSimpleName()); } catch (IllegalStateException e) { sendError(500, StatusCodes.Bad_UnexpectedError, e.getMessage()); return; } catch (IOException e) { sendError(400, StatusCodes.Bad_UnexpectedError, e.getMessage()); return; } catch (DecodingException e) { sendError(400, StatusCodes.Bad_RequestTypeInvalid, e.getMessage()); return; } // Handle request endpoint.handleMessage(this); }
From source file:com.alading.library.util.http.BinaryHttpResponseHandler.java
@Override protected void sendResponseMessage(HttpResponse response, String requset) { StatusLine status = response.getStatusLine(); Header[] contentTypeHeaders = response.getHeaders("Content-Type"); byte[] responseBody = null; if (contentTypeHeaders.length != 1) { //malformed/ambiguous HTTP Header, ABORT! sendFailureMessage(new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"), responseBody, requset); return;/*from w w w . j a v a 2 s . co m*/ } Header contentTypeHeader = contentTypeHeaders[0]; boolean foundAllowedContentType = false; for (String anAllowedContentType : mAllowedContentTypes) { if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) { foundAllowedContentType = true; } } if (!foundAllowedContentType) { //Content-Type not in allowed list, ABORT! sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"), responseBody, requset); return; } try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if (temp != null) { entity = new BufferedHttpEntity(temp); } responseBody = EntityUtils.toByteArray(entity); } catch (IOException e) { sendFailureMessage(e, (byte[]) null, requset); } if (status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody, requset); } else { sendSuccessMessage(status.getStatusCode(), responseBody, requset); } }
From source file:com.loopj.android.http.ImageHttpResponseHandler.java
void sendResponseMessage(HttpResponse response) { StatusLine status = response.getStatusLine(); Header[] contentTypeHeaders = response.getHeaders("Content-Type"); byte[] responseBody = null; if (contentTypeHeaders.length != 1) { //malformed/ambiguous HTTP Header, ABORT! sendFailureMessage(new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"), responseBody); return;//from w w w .ja v a 2 s . c o m } Header contentTypeHeader = contentTypeHeaders[0]; boolean foundAllowedContentType = false; for (String anAllowedContentType : mAllowedContentTypes) { if (anAllowedContentType.equals(contentTypeHeader.getValue())) { foundAllowedContentType = true; } } if (!foundAllowedContentType) { //Content-Type not in allowed list, ABORT! sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"), responseBody); return; } try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if (temp != null) { entity = new BufferedHttpEntity(temp); } responseBody = EntityUtils.toByteArray(entity); } catch (IOException e) { sendFailureMessage(e, (byte[]) null); } if (status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody); } else { sendSuccessMessage(responseBody); } }
From source file:biocode.fims.ezid.EzidService.java
/** * Log into the EZID service using account credentials provided by EZID. The cookie * returned by EZID is cached in a local CookieStore for the duration of the EzidService, * and so subsequent calls using this instance of the service will function as * fully authenticated. An exception is thrown if authentication fails. * * @param username to identify the user account from EZID * @param password the secret password for this account * * @throws EzidException if authentication fails for any reason *///from ww w.j a v a2 s . c o m public void login(String username, String password) throws EzidException { String msg; try { URI serviceUri = new URI(LOGIN_SERVICE); HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme()); httpClient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING.... //System.out.println("authCache: " + authCache.toString()); ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] body = null; HttpGet httpget = new HttpGet(LOGIN_SERVICE); body = httpClient.execute(httpget, handler, localcontext); String message = new String(body); msg = parseIdentifierResponse(message); // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING.... /* org.apache.http.client.CookieStore cookieStore = httpClient.getCookieStore(); System.out.println("\n\nCookies : "); List<Cookie> cookies = cookieStore.getCookies(); for (int i = 0; i < cookies.size(); i++) { System.out.println("Cookie: " + cookies.get(i)); } */ } catch (URISyntaxException e) { //System.out.println("URI SyntaxError Exception in LOGIN"); throw new EzidException("Bad syntax for uri: " + LOGIN_SERVICE, e); } catch (ClientProtocolException e) { //System.out.println("ClientProtocol Exception in LOGIN"); throw new EzidException(e); } catch (IOException e) { //System.out.println("IO Exception in LOGIN"); throw new EzidException(e); } //System.out.println("Seems to be a successful LOGIN, msg= " + msg.toString()); }
From source file:com.klinker.android.twitter.utils.api_helper.TwitterDMPicHelper.java
public Bitmap getDMPicture(String picUrl, Twitter twitter) { try {//from w w w . j a va2s .co m AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "GET"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; String twitter_endpoint = picUrl; String twitter_endpoint_host = picUrl.substring(0, picUrl.indexOf("1.1")).replace("https://", "") .replace("/", ""); String twitter_endpoint_path = picUrl.replace("ton.twitter.com", "").replace("https://", ""); String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); Log.v("talon_dm_image", "endpoint_host: " + twitter_endpoint_host); Log.v("talon_dm_image", "endpoint_path: " + twitter_endpoint_path); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET", twitter_endpoint_path); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); StatusLine statusLine = response2.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200 || statusCode == 302) { HttpEntity entity = response2.getEntity(); byte[] bytes = EntityUtils.toByteArray(entity); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); return bitmap; } else { Log.v("talon_dm_image", statusCode + ""); } conn.close(); } catch (Exception e) { e.printStackTrace(); } return null; }