List of usage examples for java.net HttpURLConnection getContentEncoding
public String getContentEncoding()
From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java
/** * Implement a simple proxy//from w w w. ja v a2s .co m * * @param requestedURL the requested URL * @param req the HttpServletRequest * @return */ @GET @Path("proxy") public Response proxy(@QueryParam(SemlibConstants.URL_PARAM) String requestedURL, @Context HttpServletRequest req) { BufferedReader in = null; try { URL url = new URL(requestedURL); URLConnection urlConnection = url.openConnection(); int proxyConnectionTimeout = ConfigManager.getInstance().getProxyAPITimeout(); // Set base properties urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(proxyConnectionTimeout * 1000); // set max response timeout 15 sec String acceptedDataFormat = req.getHeader(SemlibConstants.HTTP_HEADER_ACCEPT); if (StringUtils.isNotBlank(acceptedDataFormat)) { urlConnection.addRequestProperty(SemlibConstants.HTTP_HEADER_ACCEPT, acceptedDataFormat); } // Open the connection urlConnection.connect(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; int statusCode = httpConnection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM) { // Follow the redirect String newLocation = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_LOCATION); httpConnection.disconnect(); if (StringUtils.isNotBlank(newLocation)) { return this.proxy(newLocation, req); } else { return Response.status(statusCode).build(); } } else if (statusCode == HttpURLConnection.HTTP_OK) { // Send the response StringBuilder sbf = new StringBuilder(); // Check if the contentType is supported boolean contentTypeSupported = false; String contentType = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_CONTENT_TYPE); List<String> supportedMimeTypes = ConfigManager.getInstance().getProxySupportedMimeTypes(); if (contentType != null) { for (String cMime : supportedMimeTypes) { if (contentType.equals(cMime) || contentType.contains(cMime)) { contentTypeSupported = true; break; } } } if (!contentTypeSupported) { httpConnection.disconnect(); return Response.status(Status.NOT_ACCEPTABLE).build(); } String contentEncoding = httpConnection.getContentEncoding(); if (StringUtils.isBlank(contentEncoding)) { contentEncoding = "UTF-8"; } InputStreamReader inStrem = new InputStreamReader((InputStream) httpConnection.getContent(), Charset.forName(contentEncoding)); in = new BufferedReader(inStrem); String inputLine; while ((inputLine = in.readLine()) != null) { sbf.append(inputLine); sbf.append("\r\n"); } in.close(); httpConnection.disconnect(); return Response.status(statusCode).header(SemlibConstants.HTTP_HEADER_CONTENT_TYPE, contentType) .entity(sbf.toString()).build(); } else { httpConnection.disconnect(); return Response.status(statusCode).build(); } } return Response.status(Status.BAD_REQUEST).build(); } catch (MalformedURLException ex) { logger.log(Level.SEVERE, null, ex); return Response.status(Status.BAD_REQUEST).build(); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } } }
From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java
/** * JSON/* w ww. j a v a2s.c o m*/ * @param appWorkSpace ? * @param source ?URL * @param target * @param args ?? * @param callbackCtx nativejs * @return JSON * @throws IOException * @throws JSONException */ private XExtensionResult download(String appWorkSpace, String source, String target, JSONArray args, XCallbackContext callbackCtx) throws JSONException { HttpURLConnection connection = null; try { boolean trustEveryone = args.optBoolean(2); String objectId = args.getString(3); if (target.contains(":")) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection); XLog.e(CLASS_NAME, ILLEGAL_ARGUMENT_EXCEPTION_NAME_CONTAINS_COLON); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } XWhiteList whiteList = mWebContext.getApplication().getAppInfo().getWhiteList(); if (null != whiteList && !whiteList.isUrlWhiteListed(source)) { XLog.e(CLASS_NAME, "Source URL is not in white list: '" + source + "'"); JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection); return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error); } File file = new File(appWorkSpace, target); if (!XFileUtils.isFileAncestorOf(appWorkSpace, file.getCanonicalPath())) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection); XLog.e(CLASS_NAME, ILLEGAL_ARGUMENT_EXCEPTION_NOT_IN_ROOT_DIR); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } file.getParentFile().mkdirs(); // ? URL url = new URL(source); //TODO:?????? connection = getURLConnection(url, trustEveryone); ; connection.setRequestMethod("GET"); connection.setConnectTimeout(CONNECTION_TIME_OUT_MILLISECONDS); setCookieProperty(connection, source); connection.connect(); XLog.d(CLASS_NAME, "Download file:" + url); InputStream inputStream = connection.getInputStream(); byte[] buffer = new byte[XConstant.BUFFER_LEN]; int bytesRead = 0; long totalBytes = 0; FileTransferProgress progress = new FileTransferProgress(); if (connection.getContentEncoding() == null) { progress.setLengthComputable(true); progress.setTotal(connection.getContentLength()); } FileOutputStream outputStream = new FileOutputStream(file); while ((bytesRead = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, bytesRead); totalBytes += bytesRead; if (objectId != null) { //?js??object ID? progress.setLoaded(totalBytes); XExtensionResult progressResult = new XExtensionResult(XExtensionResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); callbackCtx.sendExtensionResult(progressResult); } synchronized (abortTriggered) { if (objectId != null && abortTriggered.contains(objectId)) { abortTriggered.remove(objectId); throw new AbortException(ABORT_EXCEPTION_DOWNLOAD_ABORTED); } } } outputStream.close(); inputStream.close(); XLog.d(CLASS_NAME, "Saved file: " + target); JSONObject entry = XFileUtils.getEntry(appWorkSpace, file); // if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) { ((HttpsURLConnection) connection).setHostnameVerifier(mDefaultHostnameVerifier); HttpsURLConnection.setDefaultSSLSocketFactory(mDefaultSSLSocketFactory); } return new XExtensionResult(XExtensionResult.Status.OK, entry); } catch (AbortException e) { JSONObject error = createFileTransferError(ABORTED_ERR, source, target, connection); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (MalformedURLException e) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, connection); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (Exception e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java
public String doRedirect(String urlRedirect) { // android.os.Debug.waitForDebugger(); try {/*w ww. j a v a 2 s .c o m*/ Log.d(TAG, "mOcp.m_redirect_uri=" + mOcp.m_redirect_uri); Log.d(TAG, "urlRedirect=" + urlRedirect); // with server phpOIDC, check for '#' if ((urlRedirect.startsWith(mOcp.m_redirect_uri + "?")) || (urlRedirect.startsWith(mOcp.m_redirect_uri + "#"))) { Log.d(TAG, "doRedirect : in check"); String[] params = urlRedirect.substring(mOcp.m_redirect_uri.length() + 1).split("&"); String code = ""; String state = ""; String state_key = "state"; for (int i = 0; i < params.length; i++) { String param = params[i]; int idxEqual = param.indexOf('='); if (idxEqual >= 0) { String key = param.substring(0, idxEqual); String value = param.substring(idxEqual + 1); if (key.startsWith("code")) code = value; if (key.startsWith("state")) state = value; if (key.startsWith("session_state")) { state = value; state_key = "session_state"; } } } // display code and state Logd(TAG, "doRedirect => code: " + code + " / state: " + state); // doRepost(code,state); if (code.length() > 0) { // get token_endpoint endpoint String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url); Log.d(TAG, "token_endpoint=" + token_endpoint); if (isEmpty(token_endpoint)) { Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url); return null; } List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); HttpURLConnection huc = getHUC(token_endpoint); huc.setInstanceFollowRedirects(false); if (mUsePrivateKeyJWT) { nameValuePairs.add(new BasicNameValuePair("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")); String client_assertion = secureProxy.getPrivateKeyJwt(token_endpoint); Logd(TAG, "client_assertion: " + client_assertion); nameValuePairs.add(new BasicNameValuePair("client_assertion", client_assertion)); } else { huc.setRequestProperty("Authorization", "Basic " + secureProxy.getClientSecretBasic()); } huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); huc.setDoOutput(true); huc.setChunkedStreamingMode(0); OutputStream os = huc.getOutputStream(); OutputStreamWriter out = new OutputStreamWriter(os, "UTF-8"); BufferedWriter writer = new BufferedWriter(out); nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code")); Logd(TAG, "code: " + code); nameValuePairs.add(new BasicNameValuePair("code", code)); nameValuePairs.add(new BasicNameValuePair("redirect_uri", mOcp.m_redirect_uri)); Logd(TAG, "redirect_uri" + mOcp.m_redirect_uri); if (state != null && state.length() > 0) nameValuePairs.add(new BasicNameValuePair(state_key, state)); // write URL encoded string from list of key value pairs writer.write(getQuery(nameValuePairs)); writer.flush(); writer.close(); out.close(); os.close(); Logd(TAG, "doRedirect => before connect"); Logd(TAG, "huc=" + huc.toString()); huc.connect(); Logd(TAG, "huc2=" + huc.getContentEncoding()); int responseCode = huc.getResponseCode(); System.out.println("2 - code " + responseCode); Log.d(TAG, "doRedirect => responseCode " + responseCode); InputStream in = null; try { in = new BufferedInputStream(huc.getInputStream()); } catch (IOException ioe) { sysout("io exception: " + huc.getErrorStream()); } if (in != null) { String result = convertStreamToString(in); // now you have the string representation of the HTML request in.close(); Logd(TAG, "doRedirect: " + result); // save as static for now return result; } else { Logd(TAG, "doRedirect null"); } } } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java
private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status) throws IOException { AQUtility.debug("multipart", url); HttpURLConnection conn = null; DataOutputStream dos = null;// w w w . ja v a2 s. c o m URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(NET_TIMEOUT * 4); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary); if (headers != null) { for (String name : headers.keySet()) { conn.setRequestProperty(name, headers.get(name)); } } String cookie = makeCookie(); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } if (ah != null) { ah.applyToken(this, conn); } dos = new DataOutputStream(conn.getOutputStream()); Object o = null; if (progress != null) { o = progress.get(); } Progress p = null; if (o != null) { p = new Progress(o); } for (Map.Entry<String, Object> entry : params.entrySet()) { writeObject(dos, entry.getKey(), entry.getValue(), p); } dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); conn.connect(); int code = conn.getResponseCode(); String message = conn.getResponseMessage(); byte[] data = null; String encoding = conn.getContentEncoding(); String error = null; if ((code < 200) || (code >= 300)) { error = new String(toData(encoding, conn.getErrorStream()), "UTF-8"); AQUtility.debug("error", error); } else { data = toData(encoding, conn.getInputStream()); } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null); }
From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java
private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status) throws IOException { AQUtility.debug("multipart", url); HttpURLConnection conn = null; DataOutputStream dos = null;// w w w . j ava 2s . c om URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(NET_TIMEOUT * 4); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary); if (headers != null) { for (String name : headers.keySet()) { conn.setRequestProperty(name, headers.get(name)); } } String cookie = makeCookie(); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } if (ah != null) { ah.applyToken(this, conn); } dos = new DataOutputStream(conn.getOutputStream()); for (Map.Entry<String, Object> entry : params.entrySet()) { writeObject(dos, entry.getKey(), entry.getValue()); } dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); conn.connect(); int code = conn.getResponseCode(); String message = conn.getResponseMessage(); byte[] data = null; String encoding = conn.getContentEncoding(); String error = null; if (code < 200 || code >= 300) { error = new String(toData(encoding, conn.getErrorStream()), "UTF-8"); AQUtility.debug("error", error); } else { data = toData(encoding, conn.getInputStream()); } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null); }
From source file:com.gotraveling.external.androidquery.callback.AbstractAjaxCallback.java
private void httpMulti(String url, Map<String, String> headers, Map<String, Object> params, AjaxStatus status) throws IOException { AQUtility.debug("multipart", url); HttpURLConnection conn = null; DataOutputStream dos = null;//from w w w .j ava 2 s .c o m URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(NET_TIMEOUT * 4); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8;boundary=" + boundary); if (headers != null) { for (String name : headers.keySet()) { conn.setRequestProperty(name, headers.get(name)); } } String cookie = makeCookie(); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } if (ah != null) { ah.applyToken(this, conn); } dos = new DataOutputStream(conn.getOutputStream()); Object o = null; if (progress != null) { o = progress.get(); } Progress p = null; if (o != null) { p = new Progress(o); } for (Map.Entry<String, Object> entry : params.entrySet()) { writeObject(dos, entry.getKey(), entry.getValue(), p); } dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); conn.connect(); int code = conn.getResponseCode(); String message = conn.getResponseMessage(); byte[] data = null; String encoding = conn.getContentEncoding(); String error = null; if (code < 200 || code >= 300) { error = new String(toData(encoding, conn.getErrorStream()), "UTF-8"); AQUtility.debug("error", error); } else { data = toData(encoding, conn.getInputStream()); } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).redirect(url).time(new Date()).data(data).error(error).client(null); }
From source file:org.apache.cordova.core.FileTransfer.java
/** * Downloads a file form a given URL and saves it to the specified directory. * * @param source URL of the server to receive the file * @param target Full path of the file on the file system *///w ww.ja v a 2s .c om private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.d(LOG_TAG, "download " + source + " to " + target); final CordovaResourceApi resourceApi = webView.getResourceApi(); final boolean trustEveryone = args.optBoolean(2); final String objectId = args.getString(3); final JSONObject headers = args.optJSONObject(4); final Uri sourceUri = resourceApi.remapUri(Uri.parse(source)); // Accept a path or a URI for the source. Uri tmpTarget = Uri.parse(target); final Uri targetUri = resourceApi .remapUri(tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target))); int uriType = CordovaResourceApi.getUriType(sourceUri); final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP; if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0); Log.e(LOG_TAG, "Unsupported URI: " + targetUri); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } // TODO: refactor to also allow resources & content: if (!isLocalTransfer && !Config.isUrlWhiteListed(source)) { Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'"); JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } final RequestContext context = new RequestContext(source, target, callbackContext); synchronized (activeRequests) { activeRequests.put(objectId, context); } cordova.getThreadPool().execute(new Runnable() { public void run() { if (context.aborted) { return; } HttpURLConnection connection = null; HostnameVerifier oldHostnameVerifier = null; SSLSocketFactory oldSocketFactory = null; File file = null; PluginResult result = null; TrackingInputStream inputStream = null; OutputStream outputStream = null; try { OpenForReadResult readResult = null; outputStream = resourceApi.openOutputStream(targetUri); file = resourceApi.mapUriToFile(targetUri); context.targetFile = file; Log.d(LOG_TAG, "Download file:" + sourceUri); FileProgressResult progress = new FileProgressResult(); if (isLocalTransfer) { readResult = resourceApi.openForRead(sourceUri); if (readResult.length != -1) { progress.setLengthComputable(true); progress.setTotal(readResult.length); } inputStream = new SimpleTrackingInputStream(readResult.inputStream); } else { // connect to server // Open a HTTP connection to the URL based on protocol connection = resourceApi.createHttpConnection(sourceUri); if (useHttps && trustEveryone) { // Setup the HTTPS connection class to trust everyone HttpsURLConnection https = (HttpsURLConnection) connection; oldSocketFactory = trustAllHosts(https); // Save the current hostnameVerifier oldHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); } connection.setRequestMethod("GET"); // TODO: Make OkHttp use this CookieManager by default. String cookie = CookieManager.getInstance().getCookie(sourceUri.toString()); if (cookie != null) { connection.setRequestProperty("cookie", cookie); } // This must be explicitly set for gzip progress tracking to work. connection.setRequestProperty("Accept-Encoding", "gzip"); // Handle the other headers if (headers != null) { addHeadersToRequest(connection, headers); } connection.connect(); if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) { // Only trust content-length header if we understand // the encoding -- identity or gzip progress.setLengthComputable(true); progress.setTotal(connection.getContentLength()); } inputStream = getInputStream(connection); } try { synchronized (context) { if (context.aborted) { return; } context.currentInputStream = inputStream; } // write bytes to file byte[] buffer = new byte[MAX_BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, bytesRead); // Send a progress event. progress.setLoaded(inputStream.getTotalRawBytesRead()); PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); context.sendPluginResult(progressResult); } } finally { context.currentInputStream = null; safeClose(inputStream); safeClose(outputStream); } Log.d(LOG_TAG, "Saved file: " + target); // create FileEntry object JSONObject fileEntry = FileUtils.getEntry(file); result = new PluginResult(PluginResult.Status.OK, fileEntry); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); result = new PluginResult(PluginResult.Status.JSON_EXCEPTION); } catch (Throwable e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } finally { safeClose(outputStream); synchronized (activeRequests) { activeRequests.remove(objectId); } if (connection != null) { // Revert back to the proper verifier and socket factories if (trustEveryone && useHttps) { HttpsURLConnection https = (HttpsURLConnection) connection; https.setHostnameVerifier(oldHostnameVerifier); https.setSSLSocketFactory(oldSocketFactory); } } if (result == null) { result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection)); } // Remove incomplete download. if (result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) { file.delete(); } context.sendPluginResult(result); } } }); }
From source file:cgeo.geocaching.cgBase.java
private static InputStream getInputstreamFromConnection(HttpURLConnection connection) throws IOException { final String encoding = connection.getContentEncoding(); InputStream ins;/*from w w w. j a v a 2 s.co m*/ if (encoding != null && encoding.equalsIgnoreCase("gzip")) { ins = new GZIPInputStream(connection.getInputStream()); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true)); } else { ins = connection.getInputStream(); } return ins; }
From source file:com.adobe.phonegap.contentsync.Sync.java
private boolean download(final String source, final File file, final JSONObject headers, final ProgressEvent progress, final CallbackContext callbackContext, final boolean trustEveryone) { Log.d(LOG_TAG, "download " + source); if (!Patterns.WEB_URL.matcher(source).matches()) { sendErrorMessage("Invalid URL", INVALID_URL_ERROR, callbackContext); return false; }/* w w w. ja v a2 s . co m*/ final CordovaResourceApi resourceApi = webView.getResourceApi(); final Uri sourceUri = resourceApi.remapUri(Uri.parse(source)); int uriType = CordovaResourceApi.getUriType(sourceUri); final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP; synchronized (progress) { if (progress.isAborted()) { return false; } } HttpURLConnection connection = null; HostnameVerifier oldHostnameVerifier = null; SSLSocketFactory oldSocketFactory = null; PluginResult result = null; TrackingInputStream inputStream = null; boolean cached = false; OutputStream outputStream = null; try { OpenForReadResult readResult = null; final Uri targetUri = resourceApi.remapUri(Uri.fromFile(file)); progress.setTargetFile(file); progress.setStatus(STATUS_DOWNLOADING); Log.d(LOG_TAG, "Download file: " + sourceUri); Log.d(LOG_TAG, "Target file: " + file); Log.d(LOG_TAG, "size = " + file.length()); if (isLocalTransfer) { readResult = resourceApi.openForRead(sourceUri); if (readResult.length != -1) { progress.setTotal(readResult.length); } inputStream = new SimpleTrackingInputStream(readResult.inputStream); } else { // connect to server // Open a HTTP connection to the URL based on protocol connection = resourceApi.createHttpConnection(sourceUri); if (useHttps && trustEveryone) { // Setup the HTTPS connection class to trust everyone HttpsURLConnection https = (HttpsURLConnection) connection; oldSocketFactory = trustAllHosts(https); // Save the current hostnameVerifier oldHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); } connection.setRequestMethod("GET"); // TODO: Make OkHttp use this CookieManager by default. String cookie = getCookies(sourceUri.toString()); if (cookie != null) { connection.setRequestProperty("cookie", cookie); } // This must be explicitly set for gzip progress tracking to work. connection.setRequestProperty("Accept-Encoding", "gzip"); // Handle the other headers if (headers != null) { addHeadersToRequest(connection, headers); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { cached = true; connection.disconnect(); sendErrorMessage("Resource not modified: " + source, CONNECTION_ERROR, callbackContext); return false; } else { if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) { // Only trust content-length header if we understand // the encoding -- identity or gzip int connectionLength = connection.getContentLength(); if (connectionLength != -1) { if (connectionLength > getFreeSpace()) { cached = true; connection.disconnect(); sendErrorMessage("Not enough free space to download", CONNECTION_ERROR, callbackContext); return false; } else { progress.setTotal(connectionLength); } } } inputStream = getInputStream(connection); } } if (!cached) { try { synchronized (progress) { if (progress.isAborted()) { return false; } //progress.connection = connection; } // write bytes to file byte[] buffer = new byte[MAX_BUFFER_SIZE]; int bytesRead = 0; outputStream = resourceApi.openOutputStream(targetUri); while ((bytesRead = inputStream.read(buffer)) > 0) { synchronized (progress) { if (progress.isAborted()) { return false; } } Log.d(LOG_TAG, "bytes read = " + bytesRead); outputStream.write(buffer, 0, bytesRead); // Send a progress event. progress.setLoaded(inputStream.getTotalRawBytesRead()); updateProgress(callbackContext, progress); } } finally { synchronized (progress) { //progress.connection = null; } safeClose(inputStream); safeClose(outputStream); } } } catch (Throwable e) { sendErrorMessage(e.getLocalizedMessage(), CONNECTION_ERROR, callbackContext); } finally { if (connection != null) { // Revert back to the proper verifier and socket factories if (trustEveryone && useHttps) { HttpsURLConnection https = (HttpsURLConnection) connection; https.setHostnameVerifier(oldHostnameVerifier); https.setSSLSocketFactory(oldSocketFactory); } } } return true; }
From source file:com.remobile.filetransfer.FileTransfer.java
/** * Downloads a file form a given URL and saves it to the specified directory. * * @param source URL of the server to receive the file * @param target Full path of the file on the file system *//* w w w . j a v a 2 s. com*/ private void download(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.d(LOG_TAG, "download " + source + " to " + target); final CordovaResourceApi resourceApi = new CordovaResourceApi(getReactApplicationContext()); final boolean trustEveryone = args.optBoolean(2); final String objectId = args.getString(3); final JSONObject headers = args.optJSONObject(4); final Uri sourceUri = resourceApi.remapUri(Uri.parse(source)); // Accept a path or a URI for the source. Uri tmpTarget = Uri.parse(target); final Uri targetUri = resourceApi .remapUri(tmpTarget.getScheme() != null ? tmpTarget : Uri.fromFile(new File(target))); int uriType = CordovaResourceApi.getUriType(sourceUri); final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; final boolean isLocalTransfer = !useHttps && uriType != CordovaResourceApi.URI_TYPE_HTTP; if (uriType == CordovaResourceApi.URI_TYPE_UNKNOWN) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null); Log.e(LOG_TAG, "Unsupported URI: " + sourceUri); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } final RequestContext context = new RequestContext(source, target, callbackContext); synchronized (activeRequests) { activeRequests.put(objectId, context); } this.cordova.getThreadPool().execute(new Runnable() { public void run() { if (context.aborted) { return; } HttpURLConnection connection = null; HostnameVerifier oldHostnameVerifier = null; SSLSocketFactory oldSocketFactory = null; File file = null; PluginResult result = null; TrackingInputStream inputStream = null; boolean cached = false; OutputStream outputStream = null; try { CordovaResourceApi.OpenForReadResult readResult = null; file = resourceApi.mapUriToFile(targetUri); context.targetFile = file; Log.d(LOG_TAG, "Download file:" + sourceUri); FileProgressResult progress = new FileProgressResult(); if (isLocalTransfer) { readResult = resourceApi.openForRead(sourceUri); if (readResult.length != -1) { progress.setLengthComputable(true); progress.setTotal(readResult.length); } inputStream = new SimpleTrackingInputStream(readResult.inputStream); } else { // connect to server // Open a HTTP connection to the URL based on protocol connection = resourceApi.createHttpConnection(sourceUri); if (useHttps && trustEveryone) { // Setup the HTTPS connection class to trust everyone HttpsURLConnection https = (HttpsURLConnection) connection; oldSocketFactory = trustAllHosts(https); // Save the current hostnameVerifier oldHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); } connection.setRequestMethod("GET"); // This must be explicitly set for gzip progress tracking to work. connection.setRequestProperty("Accept-Encoding", "gzip"); // Handle the other headers if (headers != null) { addHeadersToRequest(connection, headers); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { cached = true; connection.disconnect(); Log.d(LOG_TAG, "Resource not modified: " + source); JSONObject error = createFileTransferError(NOT_MODIFIED_ERR, source, target, connection, null); result = new PluginResult(PluginResult.Status.ERROR, error); } else { if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) { // Only trust content-length header if we understand // the encoding -- identity or gzip if (connection.getContentLength() != -1) { progress.setLengthComputable(true); progress.setTotal(connection.getContentLength()); } } inputStream = getInputStream(connection); } } if (!cached) { try { synchronized (context) { if (context.aborted) { return; } context.connection = connection; } // write bytes to file byte[] buffer = new byte[MAX_BUFFER_SIZE]; int bytesRead = 0; outputStream = resourceApi.openOutputStream(targetUri); while ((bytesRead = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, bytesRead); // Send a progress event. progress.setLoaded(inputStream.getTotalRawBytesRead()); FileTransfer.this.sendJSEvent("DownloadProgress-" + objectId, JsonConvert.jsonToReact(progress.toJSONObject())); } } finally { synchronized (context) { context.connection = null; } safeClose(inputStream); safeClose(outputStream); } Log.d(LOG_TAG, "Saved file: " + target); file = resourceApi.mapUriToFile(targetUri); context.targetFile = file; result = new PluginResult(PluginResult.Status.OK, targetUri.getPath()); } } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection, e); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); result = new PluginResult(PluginResult.Status.JSON_EXCEPTION); } catch (Throwable e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, e); Log.e(LOG_TAG, error.toString(), e); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } finally { synchronized (activeRequests) { activeRequests.remove(objectId); } if (connection != null) { // Revert back to the proper verifier and socket factories if (trustEveryone && useHttps) { HttpsURLConnection https = (HttpsURLConnection) connection; https.setHostnameVerifier(oldHostnameVerifier); https.setSSLSocketFactory(oldSocketFactory); } } if (result == null) { result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection, null)); } // Remove incomplete download. if (!cached && result.status.ordinal() != PluginResult.Status.OK.ordinal() && file != null) { file.delete(); } context.sendPluginResult(result); } } }); }