List of usage examples for java.net HttpURLConnection getContentLength
public int getContentLength()
From source file:at.spardat.xma.boot.transport.HTTPTransport.java
private Result getResourceImpl(IRtXMASessionClient session, URL url, long modifiedSince, String etag) throws CommunicationException { /* locals ---------------------------------- */ Result result = new Result(); int code = 0; HttpURLConnection conn; /* locals ---------------------------------- */ try {// ww w.ja v a2s . c o m conn = (HttpURLConnection) url.openConnection(); if (conn instanceof HttpsURLConnection) { ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier); } sendCookies(session, url, conn); if (etag != null) { conn.setRequestProperty("If-None-Match", etag); //$NON-NLS-1$ } String strUrl = url.toExternalForm(); if (url.getQuery() == null && (strUrl.endsWith(".jar") || strUrl.endsWith(".xml"))) { conn.setRequestProperty(Statics.HTTP_CACHE_CONTROL, Statics.HTTP_MAX_AGE + "=0"); //$NON-NLS-1$ } if (modifiedSince > 0) { // see sun bugid: 4397096 // if HTTP_Util library is used, the original method may also be used. // conn.setIfModifiedSince(modifiedSince); conn.setRequestProperty(Statics.strIfModifiedSince, HTTPTransport.httpDate(modifiedSince)); } conn.setRequestProperty(Statics.HTTP_ACCEPT, "*/*"); //$NON-NLS-1$ conn.setRequestProperty(Statics.HTTP_USER_AGENT, Statics.HTTP_USER_AGENT_NAME); } catch (IOException exc) { log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' form server:", exc); //$NON-NLS-1$ throw new ConnectException("error loading '" + url.toString() + "' form server:", exc); } try { code = conn.getResponseCode(); if (code == HttpURLConnection.HTTP_NOT_MODIFIED) { result.contentLength_ = 0; result.lastModified_ = conn.getLastModified(); if (result.lastModified_ <= 0) { result.lastModified_ = modifiedSince; } result.expirationDate_ = conn.getExpiration(); result.etag_ = conn.getHeaderField(Statics.strEtag); if (result.etag_ == null) { result.etag_ = etag; } log_.log(LogLevel.FINE, "resource not modified: {0}", url.toExternalForm()); //$NON-NLS-1$ } else if (code == HttpURLConnection.HTTP_OK) { result.contentLength_ = conn.getContentLength(); result.lastModified_ = conn.getLastModified(); result.expirationDate_ = conn.getExpiration(); result.etag_ = conn.getHeaderField(Statics.strEtag); result.transformations_ = conn.getHeaderField(Statics.TRANSFORM_HEADER); result.setBuffer(this.readOutput(conn)); if (result.contentLength_ < 0) { result.contentLength_ = result.buffer_.length; } } else if (code == HttpURLConnection.HTTP_MOVED_TEMP || code == HttpURLConnection.HTTP_MOVED_PERM) { String location = conn.getHeaderField(Statics.HTTP_LOCATION); throw new RedirectException("redirect received from " + url.toString() + " to " + location, code, location); } else { if (code < 500) throw new ConnectException("error loading '" + url.toString() + "' from the server:", code); else throw new ServerException("error loading '" + url.toString() + "' from the server:", code); } readCookies(session, url, conn); } catch (RedirectException re) { throw re; } catch (CommunicationException ce) { if (code != 0) log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$ log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' from the server:", ce); //$NON-NLS-1$ throw ce; } catch (Exception ex) { if (code != 0) log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$ log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' from the server:", ex); //$NON-NLS-1$ if (code < 500) throw new ConnectException("error loading '" + url.toString() + "' from the server:", ex); else throw new ServerException("error loading '" + url.toString() + "' from the server:", ex); } return result; }
From source file:eionet.cr.harvest.PullHarvest.java
/** * * @param urlConn/*from w w w.j a v a2 s . c o m*/ * @param responseCode * @param exception * @throws DAOException */ private void addSourceMetadata(HttpURLConnection urlConn, int responseCode, String responseMessage, Exception exception) { String firstSeen = formatDate(getContextSourceDTO().getTimeCreated()); String lastRefreshed = formatDate(new Date()); addSourceMetadata(Predicates.CR_FIRST_SEEN, ObjectDTO.createLiteral(firstSeen, XMLSchema.DATETIME)); addSourceMetadata(Predicates.CR_LAST_REFRESHED, ObjectDTO.createLiteral(lastRefreshed, XMLSchema.DATETIME)); if (isError(responseCode)) { if (responseMessage == null) { responseMessage = ""; } addSourceMetadata(Predicates.CR_ERROR_MESSAGE, ObjectDTO.createLiteral( "Server returned error: " + responseMessage + " (HTTP response code: " + responseCode + ")")); } else if (exception != null) { addSourceMetadata(Predicates.CR_ERROR_MESSAGE, ObjectDTO.createLiteral(exception.toString())); } if (urlConn != null) { // content type String contentType = getSourceContentType(urlConn); if (!StringUtils.isBlank(contentType)) { addSourceMetadata(Predicates.CR_MEDIA_TYPE, ObjectDTO.createLiteral(contentType)); // if content type is not "application/rdf+xml", generate rdf:type from the // DublinCore type mappings if (!contentType.toLowerCase().startsWith("application/rdf+xml")) { String rdfType = MediaTypeToDcmiTypeConverter.getDcmiTypeFor(contentType); if (rdfType != null) { addSourceMetadata(Predicates.RDF_TYPE, ObjectDTO.createResource(rdfType)); } } } // content's last modification long contentLastModified = urlConn.getLastModified(); if (contentLastModified > 0) { String lastModifString = formatDate(new Date(contentLastModified)); addSourceMetadata(Predicates.CR_LAST_MODIFIED, ObjectDTO.createLiteral(lastModifString, XMLSchema.DATETIME)); } // content size int contentLength = urlConn.getContentLength(); if (contentLength >= 0) { addSourceMetadata(Predicates.CR_BYTE_SIZE, ObjectDTO.createLiteral(contentLength)); } } }
From source file:com.acc.android.network.operator.base.BaseHttpOperator.java
public byte[] getByteArray(String url, RequestMethod requestMethod, Object paramObject, RequestListener fileDownloadListener) { if (!this.hasInternet(context)) { fileDownloadListener.onFail(RequestFailReason._NET); return null; }/*w ww. j a v a 2 s . c om*/ HttpURLConnection httpURLConnection = null; InputStream inputStream = null; ByteArrayOutputStream byteArrayOutputStream = null; try { byte[] bytes = null; LogUtil.info(this, "Begin a request--->>>>>>>>>>"); if (requestMethod == requestMethod.GET && paramObject != null) { url = url + "?" + this.encodeUrlParam(paramObject); } LogUtil.info(this, "url:", url); LogUtil.info(this, "requestMathod:", requestMethod); LogUtil.info(this, "paramObject:", paramObject); httpURLConnection = (HttpURLConnection) new URL(url).openConnection(); if (this.sessionStr != null) { httpURLConnection.setRequestProperty("cookie", sessionStr); // httpURLConnection.setRequestProperty("Accept-Encoding", // "identity"); } httpURLConnection.setConnectTimeout(5 * 1000); if (requestMethod == RequestMethod.GET) { httpURLConnection.setRequestMethod("GET"); // httpURLConnection.setRequestProperty("Content-Type", // "application/x-www-form-urlencode"); httpURLConnection.setRequestProperty("Accept-Encoding", "identity"); // System.out.println("BBBBBBBBBBVVVVVVVVVVV"); httpURLConnection.connect(); } else { httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencode"); if (paramObject != null) { httpURLConnection.getOutputStream() .write(this.encodeUrlParam(paramObject).getBytes(HttpConstant.ENCODE)); } } double contentLength = httpURLConnection.getContentLength(); inputStream = httpURLConnection.getInputStream(); if (inputStream != null) { byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buf = new byte[128]; // System.out.println(contentLength); int read = -1; long downloadCount = 0; while ((read = inputStream.read(buf)) != -1) { byteArrayOutputStream.write(buf, 0, read); downloadCount += read; fileDownloadListener.onProgress(downloadCount, contentLength); } bytes = byteArrayOutputStream.toByteArray(); } LogUtil.info(this, "End a request successfully---VVVVVVVVVV"); LogUtil.info(this, "response:", bytes == null); fileDownloadListener.onSuccess(bytes); return bytes; } catch (Exception e) { LogUtil.info(this, "End a request with exception below---XXXXXXXXXX"); fileDownloadListener.onFail(RequestFailReason.EXCEPTION); e.printStackTrace(); return null; } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } StreamUtil.closeStream(byteArrayOutputStream); StreamUtil.closeStream(inputStream); } }
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 *///from w ww . jav a 2s .co m 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: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; }/*from w ww. j a v a 2 s.c o 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:easyshop.downloadhelper.HttpPageGetter.java
public HttpPage getDHttpPage(PageRef url, String charSet) { count++;/*from w w w . j a v a2 s . co m*/ log.debug("getURL(" + count + ")"); if (url.getUrlStr() == null) { ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new OriHttpPage(-1, null, null, null, conRes, null); } URL requestedURL = null; try { requestedURL = new URL(url.getUrlStr()); } catch (MalformedURLException e1) { // TODO Auto-generated catch block log.error("wrong urlstr" + url.getUrlStr()); ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new OriHttpPage(-1, null, null, null, conRes, null); } ; // System.out.println(""+requestedURL.toExternalForm()); URL referer = null; try { log.debug("Creating HTTP connection to " + requestedURL); HttpURLConnection conn = (HttpURLConnection) requestedURL.openConnection(); if (referer != null) { log.debug("Setting Referer header to " + referer); conn.setRequestProperty("Referer", referer.toExternalForm()); } if (userAgent != null) { log.debug("Setting User-Agent to " + userAgent); conn.setRequestProperty("User-Agent", userAgent); } // DateFormat dateFormat=DateFormat.getDateInstance(); // conn.setRequestProperty("If-Modlfied-Since",dateFormat.parse("2005-08-15 20:18:30").toGMTString()); conn.setUseCaches(false); // conn.setRequestProperty("connection","keep-alive"); for (Iterator it = conn.getRequestProperties().keySet().iterator(); it.hasNext();) { String key = (String) it.next(); if (key == null) { break; } String value = conn.getHeaderField(key); // System.out.println("Request header " + key + ": " + value); } log.debug("Opening URL"); long startTime = System.currentTimeMillis(); conn.connect(); String resp = conn.getResponseMessage(); log.debug("Remote server response: " + resp); int code = conn.getResponseCode(); if (code != 200) { log.error("Could not get connection for code=" + code); System.err.println("Could not get connection for code=" + code); ConnResponse conRes = new ConnResponse(null, null, 0, 0, code); return new HttpPage(requestedURL.toExternalForm(), null, conRes, null); } // if (conn.getContentLength()<=0||conn.getContentLength()>10000000){ // log.error("Content length==0"); // System.err.println("Content length==0"); // ConnResponse conRes=new ConnResponse(null,null,null,0,0,-100); // return new URLObject(-1,requestedURL, null,null,conRes); // } String respStr = conn.getHeaderField(0); long serverDate = conn.getDate(); // log.info("Server response: " + respStr); for (int i = 1; i < conn.getHeaderFields().size(); i++) { String key = conn.getHeaderFieldKey(i); if (key == null) { break; } String value = conn.getHeaderField(key); // System.out.println("Received header " + key + ": " + value); // log.debug("Received header " + key + ": " + value); } // log.debug("Getting buffered input stream from remote connection"); log.debug("start download(" + count + ")"); BufferedInputStream remoteBIS = new BufferedInputStream(conn.getInputStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); byte[] buf = new byte[1024]; int bytesRead = 0; while (bytesRead >= 0) { baos.write(buf, 0, bytesRead); bytesRead = remoteBIS.read(buf); } // baos.write(remoteBIS.read(new byte[conn.getContentLength()])); // remoteBIS.close(); byte[] content = baos.toByteArray(); long timeTaken = System.currentTimeMillis() - startTime; if (timeTaken < 100) timeTaken = 500; int bytesPerSec = (int) ((double) content.length / ((double) timeTaken / 1000.0)); // log.info("Downloaded " + content.length + " bytes, " + bytesPerSec + " bytes/sec"); if (content.length < conn.getContentLength()) { log.warn("Didn't download full content for URL: " + url); // failureCount++; ConnResponse conRes = new ConnResponse(conn.getContentType(), null, content.length, serverDate, code); return new HttpPage(requestedURL.toExternalForm(), null, conRes, conn.getContentType()); } log.debug("download(" + count + ")"); ConnResponse conRes = new ConnResponse(conn.getContentType(), null, conn.getContentLength(), serverDate, code); String c = charSet; if (c == null) c = conRes.getCharSet(); HttpPage obj = new HttpPage(requestedURL.toExternalForm(), content, conRes, c); return obj; } catch (IOException ioe) { log.warn("Caught IO Exception: " + ioe.getMessage(), ioe); failureCount++; ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new HttpPage(requestedURL.toExternalForm(), null, conRes, null); } catch (Exception e) { log.warn("Caught Exception: " + e.getMessage(), e); failureCount++; ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new HttpPage(requestedURL.toExternalForm(), null, conRes, null); } }
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 *//*from w w w .j a v a2 s .c o m*/ 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); } } }); }
From source file:com.cr_wd.android.network.HttpClient.java
/** * Performs a HTTP GET/POST Request/*from ww w.j a va 2 s .c om*/ * * @return id of the request */ protected int doRequest(final Method method, final String url, HttpHeaders headers, HttpParams params, final HttpHandler handler) { if (headers == null) { headers = new HttpHeaders(); } if (params == null) { params = new HttpParams(); } handler.client = this; final int requestId = incrementRequestId(); class HandlerRunnable extends Handler implements Runnable { private final Method method; private String url; private final HttpHeaders headers; private final HttpParams params; private final HttpHandler handler; private HttpResponse response; private boolean canceled = false; private int retries = 0; protected HandlerRunnable(final Method method, final String url, final HttpHeaders headers, final HttpParams params, final HttpHandler handler) { this.method = method; this.url = url; this.headers = headers; this.params = params; this.handler = handler; } @Override public void run() { execute(); } private void execute() { response = new HttpResponse(requestId, method, url); HttpURLConnection conn = null; try { /* append query string for GET requests */ if (method == Method.GET) { if (!params.urlParams.isEmpty()) { url += ('?' + params.getParamString()); } } /* setup headers for POST requests */ if (method == Method.POST) { headers.addHeader("Accept-Charset", requestOptions.encoding); if (params.hasMultipartParams()) { final SimpleMultipart multipart = params.getMultipart(); headers.addHeader("Content-Type", multipart.getContentType()); } else { headers.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + requestOptions.encoding); } } if (canceled) { postCancel(); return; } /* open and configure the connection */ conn = (HttpURLConnection) new URL(url).openConnection(); postStart(); if (method == Method.GET) { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); } else if (method == Method.POST) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); } conn.setAllowUserInteraction(false); conn.setReadTimeout(requestOptions.readTimeout); conn.setConnectTimeout(requestOptions.connectTimeout); /* add headers to the connection */ for (final Map.Entry<String, List<String>> entry : headers.getHeaders().entrySet()) { for (final String value : entry.getValue()) { conn.addRequestProperty(entry.getKey(), value); } } if (canceled) { try { conn.disconnect(); } catch (final Exception e) { } postCancel(); return; } response.requestProperties = conn.getRequestProperties(); /* do post */ if (method == Method.POST) { InputStream is; if (params.hasMultipartParams()) { is = params.getMultipart().getContent(); } else { is = new ByteArrayInputStream(params.getParamString().getBytes()); } final OutputStream os = conn.getOutputStream(); writeStream(os, is); } else { conn.connect(); } if (canceled) { try { conn.disconnect(); } catch (final Exception e) { } postCancel(); return; } response.contentEncoding = conn.getContentEncoding(); response.contentLength = conn.getContentLength(); response.contentType = conn.getContentType(); response.date = conn.getDate(); response.expiration = conn.getExpiration(); response.headerFields = conn.getHeaderFields(); response.ifModifiedSince = conn.getIfModifiedSince(); response.lastModified = conn.getLastModified(); response.responseCode = conn.getResponseCode(); response.responseMessage = conn.getResponseMessage(); /* do get */ if (conn.getResponseCode() < 400) { response.responseBody = readStream(conn.getInputStream()); postSuccess(); } else { response.responseBody = readStream(conn.getErrorStream()); response.throwable = new Exception(response.responseMessage); postError(); } } catch (final Exception e) { if (retries < requestOptions.maxRetries) { retries++; postRetry(); execute(); } else { response.responseBody = e.getMessage(); response.throwable = e; postError(); } } finally { if (conn != null) { conn.disconnect(); } } } private String readStream(final InputStream is) throws IOException { final BufferedInputStream bis = new BufferedInputStream(is); final ByteArrayBuffer baf = new ByteArrayBuffer(50); int read = 0; final byte[] buffer = new byte[8192]; while (true) { if (canceled) { break; } read = bis.read(buffer); if (read == -1) { break; } baf.append(buffer, 0, read); } try { bis.close(); } catch (final IOException e) { } try { is.close(); } catch (final IOException e) { } return new String(baf.toByteArray()); } private void writeStream(final OutputStream os, final InputStream is) throws IOException { final BufferedInputStream bis = new BufferedInputStream(is); int read = 0; final byte[] buffer = new byte[8192]; while (true) { if (canceled) { break; } read = bis.read(buffer); if (read == -1) { break; } os.write(buffer, 0, read); } if (!canceled) { os.flush(); } try { os.close(); } catch (final IOException e) { } try { bis.close(); } catch (final IOException e) { } try { is.close(); } catch (final IOException e) { } } @Override public void handleMessage(final Message msg) { if (msg.what == HttpHandler.MESSAGE_CANCEL) { canceled = true; } } private void postSuccess() { postMessage(HttpHandler.MESSAGE_SUCCESS); } private void postError() { postMessage(HttpHandler.MESSAGE_ERROR); } private void postCancel() { postMessage(HttpHandler.MESSAGE_CANCEL); } private void postStart() { postMessage(HttpHandler.MESSAGE_START); } private void postRetry() { postMessage(HttpHandler.MESSAGE_RETRY); } private void postMessage(final int what) { final Message msg = handler.obtainMessage(); msg.what = what; msg.arg1 = requestId; msg.obj = response; handler.sendMessage(msg); } } ; /* Create a new HandlerRunnable and start it */ final HandlerRunnable hr = new HandlerRunnable(method, url, headers, params, handler); requests.put(requestId, new WeakReference<Handler>(hr)); new Thread(hr).start(); /* Return with the request id */ return requestId; }
From source file:org.apache.cordova.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 .java2 s. c o m*/ 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, null); Log.e(LOG_TAG, "Unsupported URI: " + sourceUri); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } /* This code exists for compatibility between 3.x and 4.x versions of Cordova. * Previously the CordovaWebView class had a method, getWhitelist, which would * return a Whitelist object. Since the fixed whitelist is removed in Cordova 4.x, * the correct call now is to shouldAllowRequest from the plugin manager. */ Boolean shouldAllowRequest = null; if (isLocalTransfer) { shouldAllowRequest = true; } if (shouldAllowRequest == null) { try { Method gwl = webView.getClass().getMethod("getWhitelist"); Whitelist whitelist = (Whitelist) gwl.invoke(webView); shouldAllowRequest = whitelist.isUrlWhiteListed(source); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } if (shouldAllowRequest == null) { try { Method gpm = webView.getClass().getMethod("getPluginManager"); PluginManager pm = (PluginManager) gpm.invoke(webView); Method san = pm.getClass().getMethod("shouldAllowRequest", String.class); shouldAllowRequest = (Boolean) san.invoke(pm, source); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } if (!Boolean.TRUE.equals(shouldAllowRequest)) { Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'"); JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401, null); 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; boolean cached = false; OutputStream outputStream = null; try { 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"); // 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(); 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()); PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); context.sendPluginResult(progressResult); } } finally { synchronized (context) { context.connection = null; } safeClose(inputStream); safeClose(outputStream); } Log.d(LOG_TAG, "Saved file: " + target); // create FileEntry object Class webViewClass = webView.getClass(); PluginManager pm = null; try { Method gpm = webViewClass.getMethod("getPluginManager"); pm = (PluginManager) gpm.invoke(webView); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } if (pm == null) { try { Field pmf = webViewClass.getField("pluginManager"); pm = (PluginManager) pmf.get(webView); } catch (NoSuchFieldException e) { } catch (IllegalAccessException e) { } } file = resourceApi.mapUriToFile(targetUri); context.targetFile = file; FileUtils filePlugin = (FileUtils) pm.getPlugin("File"); if (filePlugin != null) { JSONObject fileEntry = filePlugin.getEntryForFile(file); if (fileEntry != null) { result = new PluginResult(PluginResult.Status.OK, fileEntry); } else { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection, null); Log.e(LOG_TAG, "File plugin cannot represent download path"); result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } } else { Log.e(LOG_TAG, "File plugin not found; cannot save downloaded file"); result = new PluginResult(PluginResult.Status.ERROR, "File plugin not found; cannot save downloaded file"); } } } 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.getStatus() != PluginResult.Status.OK.ordinal() && file != null) { file.delete(); } context.sendPluginResult(result); } } }); }
From source file:com.acc.android.network.operator.base.BaseHttpOperator.java
public byte[] openRequestForByteArray(String url, RequestMethod requestMethod, Object paramObject, HttpReqestProgressListener httpReqestProgressListener) { if (!this.checkNetWork()) { // return this.notNetError; }//from www .j a v a 2 s. c o m HttpURLConnection conn = null; InputStream inputStream = null; ByteArrayOutputStream byteArrayOutputStream = null; // Bitmap bitmap = null; byte[] bytes = null; try { // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "Begin a request--->>>>>>>>>>"); // } // try { // url = URLEncoder.encode(url, HttpConstant.ENCODE); // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } if (requestMethod == requestMethod.GET && paramObject != null) { // try { url = url + "?" + this.encodeUrlParam(paramObject); // } catch (UnsupportedEncodingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // http://192.168.15.204:82/agcom/rest/roadRest/getBestRoad?id=2&xy=56536.156809,13853.484204 // 56364.173164,12955.347386 } // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "url:", url); LogUtil.info(this, "requestMethod:", requestMethod); LogUtil.info(this, "paramObject:", paramObject); // } // url = url.replace(" ", "%20"); conn = (HttpURLConnection) new URL(url).openConnection(); // System.out // .println("this.sessionStr == null" + this.sessionStr == null); // System.out.println(this.sessionStr == null); if (this.sessionStr != null) { conn.setRequestProperty("cookie", sessionStr); } conn.setConnectTimeout(5 * 1000); if (requestMethod == RequestMethod.GET) { // conn.setRequestMethod(method); // if (isMultipart) { // conn.setRequestProperty("Content-Type", // "multipart/form-data;"); // } else { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode"); // } conn.connect(); } else { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setUseCaches(false); // http: // // 192.168.16.16:8089/agcom/rest/system/locateDiscode/231/10// // Content-Type // if (isMultipart) { // conn.setRequestProperty("Content-Type", // "multipart/form-data;"); // } else { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode"); // } // conn.setRequestProperty("Content-Type", // "application/x-www-form-urlencode"); // conn.connect(); if (paramObject != null) { conn.getOutputStream().write(this.encodeUrlParam(paramObject).getBytes(HttpConstant.ENCODE)); } } inputStream = conn.getInputStream(); if (inputStream != null) { byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buf = new byte[128]; long contentLength = conn.getContentLength(); int read = -1; long downloadCount = 0; while ((read = inputStream.read(buf)) != -1) { byteArrayOutputStream.write(buf, 0, read); downloadCount += read; // publishProgress(count * 1.0f / length); if (httpReqestProgressListener != null) { httpReqestProgressListener.onRequestProgress(downloadCount * 1f / contentLength); } } bytes = byteArrayOutputStream.toByteArray(); // File file = new File(params[1]); // if (file != null) { // FileOutputStream fos = new // FileOutputStream( // file); // fos.write(data); // fos.close(); // } // bitmap = BitmapFactory.decodeByteArray( // data, 0, data.length); // return bit; // return bytes; } // in = new BufferedInputStream(uRLConnection // .getInputStream()); // bitmap = BitmapFactory.decodeStream(inputStream); // response = read(inputStream); // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "response:", bytes == null); // } if (this.sessionStr == null) { Map<String, List<String>> cookies = conn.getHeaderFields(); // this.cookieHeader = conn.getg for (String key : cookies.keySet()) { // System.out.println("sdfdsfd:" + key); if (key == null) { continue; } if ("set-cookie".equals(key.toLowerCase())) { List<String> values = cookies.get(key); String sessionStrTemp = ""; for (String value : values) { sessionStrTemp += value; sessionStrTemp += ";"; // conn.addRequestProperty("set-cookie", string); } // loginSessionStrTemp = // loginSessionStrTemp.substring(0, // loginSessionStrTemp.length() - 1); // System.out.println("loginSessionStrTemp:" // + loginSessionStrTemp); this.sessionStr = sessionStrTemp; this.sessionKey = key; // OldHttpUtil.LOGINSESSIONSTR = sessionStrTemp; // BaseHttpManager.sessionStr = loginSessionStrTemp; break; } } // System.out.println("sessionStr:" + sessionStr); } // System.out.println("openUrl:response:" + response); } catch (Exception e) { // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "End a request with exception below---XXXXXXXXXX"); // } if (httpReqestProgressListener != null) { httpReqestProgressListener.onRequestFail(); } e.printStackTrace(); return bytes; } finally { if (conn != null) { conn.disconnect(); } if (byteArrayOutputStream != null) { try { byteArrayOutputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } // if (AppLibConstant.isUseLog()) { LogUtil.info(this, "End a request successfully---VVVVVVVVVV"); // } return bytes; }