List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:fi.cosky.sdk.API.java
private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException { URL serverAddress;//w w w. jav a2 s.com BufferedReader br; String result = ""; HttpURLConnection connection = null; String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri(); try { String method = l.getMethod(); String type = l.getType(); serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); boolean doOutput = doOutput(method); connection.setDoOutput(doOutput); connection.setRequestMethod(method); connection.setInstanceFollowRedirects(false); if (method.equals("GET") && useMimeTypes) if (type == null || type.equals("")) { addMimeTypeAcceptToRequest(object, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } if (!useMimeTypes) connection.setRequestProperty("Accept", "application/json"); if (doOutput && useMimeTypes) { //this handles the case if the link is self made and the type field has not been set. if (type == null || type.equals("")) { addMimeTypeContentTypeToRequest(l, tClass, connection); addMimeTypeAcceptToRequest(l, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } if (!useMimeTypes) connection.setRequestProperty("Content-Type", "application/json"); if (tokenData != null) { connection.addRequestProperty("Authorization", tokenData.getTokenType() + " " + tokenData.getAccessToken()); } addVersionNumberToHeader(object, url, connection); if (method.equals("POST") || method.equals("PUT")) { String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object. connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + ""); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(json); osw.flush(); osw.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) { ResponseData data = new ResponseData(); Link link = parseLocationLinkFromString(connection.getHeaderField("Location")); link.setType(type); data.setLocation(link); connection.disconnect(); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println( "Authentication expired " + connection.getResponseMessage() + " trying to reauthenticate"); if (retry && this.tokenData != null) { this.tokenData = null; retry = false; if (authenticate()) { System.out.println("Reauthentication success, will continue with " + l.getMethod() + " request on " + l.getRel()); return sendRequest(l, tClass, object); } } else throw new IOException( "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API"); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return (T) objectCache.getObject(url); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { return (T) new ResponseData(); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + method); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) { if (retry) { System.out.println("Request caused internal server error, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println("Requst caused internal server error, please contact dev@nfleet.fi"); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_GATEWAY) { if (retry) { System.out.println("Could not connect to NFleet-API, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println( "Could not connect to NFleet-API, please check service status from http://status.nfleet.fi and try again later."); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } catch (SecurityException e) { throw e; } catch (IllegalArgumentException e) { throw e; } finally { assert connection != null; connection.disconnect(); } Object newEntity = gson.fromJson(result, tClass); objectCache.addUri(url, newEntity); return (T) newEntity; }
From source file:org.opencms.staticexport.CmsAfterPublishStaticExportHandler.java
/** * Exports a single (template) resource specified by its export data.<p> * //from w w w . j a va 2 s . c o m * @param data the export data * @param cookies cookies to keep the session * * @return the status of the http request used to perform the export * * @throws IOException if the http request fails */ protected int exportTemplateResource(CmsStaticExportData data, StringBuffer cookies) throws IOException { String vfsName = data.getVfsName(); String rfsName = data.getRfsName(); CmsStaticExportManager manager = OpenCms.getStaticExportManager(); String exportUrlStr; if (rfsName.contains(manager.getRfsPrefix(vfsName))) { LOG.info("rfsName " + rfsName + " contains rfsPrefix " + manager.getRfsPrefix(vfsName)); exportUrlStr = manager.getExportUrl() + rfsName; } else { exportUrlStr = manager.getExportUrl() + manager.getRfsPrefix(vfsName) + rfsName; } if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_SENDING_REQUEST_2, rfsName, exportUrlStr)); } // setup the connection and request the resource URL exportUrl = new URL(exportUrlStr); HttpURLConnection.setFollowRedirects(false); HttpURLConnection urlcon = (HttpURLConnection) exportUrl.openConnection(); // set request type to GET urlcon.setRequestMethod(REQUEST_METHOD_GET); // add special export header urlcon.setRequestProperty(CmsRequestUtil.HEADER_OPENCMS_EXPORT, CmsStringUtil.TRUE); // add additional headers if available if (manager.getAcceptLanguageHeader() != null) { urlcon.setRequestProperty(CmsRequestUtil.HEADER_ACCEPT_LANGUAGE, manager.getAcceptLanguageHeader()); } else { urlcon.setRequestProperty(CmsRequestUtil.HEADER_ACCEPT_LANGUAGE, manager.getDefaultAcceptLanguageHeader()); } if (manager.getAcceptCharsetHeader() != null) { urlcon.setRequestProperty(CmsRequestUtil.HEADER_ACCEPT_CHARSET, manager.getAcceptCharsetHeader()); } else { urlcon.setRequestProperty(CmsRequestUtil.HEADER_ACCEPT_CHARSET, manager.getDefaultAcceptCharsetHeader()); } // get the last modified date and add it to the request String exportFileName = CmsFileUtil.normalizePath(manager.getExportPath(vfsName) + rfsName); File exportFile = new File(exportFileName); long dateLastModified = exportFile.lastModified(); // system folder case if (vfsName.startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) { // iterate over all rules Iterator<CmsStaticExportRfsRule> it = manager.getRfsRules().iterator(); while (it.hasNext()) { CmsStaticExportRfsRule rule = it.next(); if (rule.match(vfsName)) { exportFileName = CmsFileUtil.normalizePath(rule.getExportPath() + rfsName); exportFile = new File(exportFileName); if (dateLastModified > exportFile.lastModified()) { dateLastModified = exportFile.lastModified(); } } } } urlcon.setIfModifiedSince(dateLastModified); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_IF_MODIFIED_SINCE_SET_2, exportFile.getName(), new Long((dateLastModified / 1000) * 1000))); } if (cookies.length() > 0) { // set the cookies, included the session id to keep the same session urlcon.setRequestProperty(REQUEST_PROPERTY_COOKIE, cookies.toString()); } // now perform the request urlcon.connect(); int status = urlcon.getResponseCode(); if (cookies.length() == 0) { //Now retrieve the cookies. The jsessionid is here cookies.append(urlcon.getHeaderField(HEADER_FIELD_SET_COOKIE)); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_STATICEXPORT_COOKIES_1, cookies)); } } urlcon.disconnect(); if (LOG.isInfoEnabled()) { LOG.info(Messages.get().getBundle().key(Messages.LOG_REQUEST_RESULT_3, rfsName, exportUrlStr, new Integer(status))); } return status; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading * page resources as appropriate.//www . j ava 2 s . c o m * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ @Override protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { HttpURLConnection conn = null; String urlStr = url.toString(); if (log.isDebugEnabled()) { log.debug("Start : sample " + urlStr); log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth); } HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); res.setSampleLabel(urlStr); res.setURL(url); res.setHTTPMethod(method); res.sampleStart(); // Count the retries as well in the time // Check cache for an entry with an Expires header in the future final CacheManager cacheManager = getCacheManager(); if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) { if (cacheManager.inCache(url)) { return updateSampleResultForResourceInCache(res); } } try { // Sampling proper - establish the connection and read the response: // Repeatedly try to connect: int retry = -1; // Start with -1 so tries at least once, and retries at most MAX_CONN_RETRIES times for (; retry < MAX_CONN_RETRIES; retry++) { try { conn = setupConnection(url, method, res); // Attempt the connection: savedConn = conn; conn.connect(); break; } catch (BindException e) { if (retry >= MAX_CONN_RETRIES) { log.error("Can't connect after " + retry + " retries, " + e); throw e; } log.debug("Bind exception, try again"); if (conn != null) { savedConn = null; // we don't want interrupt to try disconnection again conn.disconnect(); } setUseKeepAlive(false); } catch (IOException e) { log.debug("Connection failed, giving up"); throw e; } } if (retry > MAX_CONN_RETRIES) { // This should never happen, but... throw new BindException(); } // Nice, we've got a connection. Finish sending the request: if (method.equals(HTTPConstants.POST)) { String postBody = sendPostData(conn); res.setQueryString(postBody); } else if (method.equals(HTTPConstants.PUT)) { String putBody = sendPutData(conn); res.setQueryString(putBody); } // Request sent. Now get the response: byte[] responseData = readResponse(conn, res); res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setResponseData(responseData); int errorLevel = conn.getResponseCode(); String respMsg = conn.getResponseMessage(); String hdr = conn.getHeaderField(0); if (hdr == null) { hdr = "(null)"; // $NON-NLS-1$ } if (errorLevel == -1) {// Bug 38902 - sometimes -1 seems to be returned unnecessarily if (respMsg != null) {// Bug 41902 - NPE try { errorLevel = Integer.parseInt(respMsg.substring(0, 3)); log.warn("ResponseCode==-1; parsed " + respMsg + " as " + errorLevel); } catch (NumberFormatException e) { log.warn("ResponseCode==-1; could not parse " + respMsg + " hdr: " + hdr); } } else { respMsg = hdr; // for result log.warn("ResponseCode==-1 & null ResponseMessage. Header(0)= " + hdr); } } if (errorLevel == -1) { res.setResponseCode("(null)"); // $NON-NLS-1$ } else { res.setResponseCode(Integer.toString(errorLevel)); } res.setSuccessful(isSuccessCode(errorLevel)); if (respMsg == null) {// has been seen in a redirect respMsg = hdr; // use header (if possible) if no message found } res.setResponseMessage(respMsg); String ct = conn.getContentType(); if (ct != null) { res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } String responseHeaders = getResponseHeaders(conn); res.setResponseHeaders(responseHeaders); if (res.isRedirect()) { res.setRedirectLocation(conn.getHeaderField(HTTPConstants.HEADER_LOCATION)); } // record headers size to allow HTTPSampleResult.getBytes() with different options res.setHeadersSize(responseHeaders.replaceAll("\n", "\r\n") // $NON-NLS-1$ $NON-NLS-2$ .length() + 2); // add 2 for a '\r\n' at end of headers (before data) if (log.isDebugEnabled()) { log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(conn.getURL()); } // Store any cookies received in the cookie manager: saveConnectionCookies(conn, url, getCookieManager()); // Save cache information if (cacheManager != null) { cacheManager.saveDetails(conn, res); } res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); return res; } catch (IOException e) { res.sampleEnd(); savedConn = null; // we don't want interrupt to try disconnection again // We don't want to continue using this connection, even if KeepAlive is set if (conn != null) { // May not exist conn.disconnect(); } conn = null; // Don't process again return errorResult(e, res); } finally { // calling disconnect doesn't close the connection immediately, // but indicates we're through with it. The JVM should close // it when necessary. savedConn = null; // we don't want interrupt to try disconnection again disconnect(conn); // Disconnect unless using KeepAlive } }
From source file:org.broad.igv.util.HttpUtils.java
/** * The "real" connection method/*from www. j ava 2 s.c o m*/ * * @param url * @param requestProperties * @param method * @return * @throws java.io.IOException */ private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties, String method, int redirectCount) throws IOException { //Encode query string portions url = StringUtils.encodeURLQueryString(url); if (log.isTraceEnabled()) { log.trace(url); } //Encode base portions. Right now just spaces, most common case //TODO This is a hack and doesn't work for all characters which need it if (StringUtils.countChar(url.toExternalForm(), ' ') > 0) { String newPath = url.toExternalForm().replaceAll(" ", "%20"); url = new URL(newPath); } Proxy sysProxy = null; boolean igvProxySettingsExist = proxySettings != null && proxySettings.useProxy; //Only check for system proxy if igv proxy settings not found if (!igvProxySettingsExist) { sysProxy = getSystemProxy(url.toExternalForm()); } boolean useProxy = sysProxy != null || igvProxySettingsExist; HttpURLConnection conn; if (useProxy) { Proxy proxy = sysProxy; if (igvProxySettingsExist) { if (proxySettings.type == Proxy.Type.DIRECT) { proxy = Proxy.NO_PROXY; } else { proxy = new Proxy(proxySettings.type, new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort)); } } conn = (HttpURLConnection) url.openConnection(proxy); if (igvProxySettingsExist && proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes(); String encodedUserPwd = String.valueOf(Base64Coder.encode(bytes)); conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); } } else { conn = (HttpURLConnection) url.openConnection(); } if (GSUtils.isGenomeSpace(url)) { conn.setRequestProperty("Accept", "application/json,text/plain"); } else { conn.setRequestProperty("Accept", "text/plain"); } //------// //There seems to be a bug with JWS caches //So we avoid caching //This default is persistent, really should be available statically but isn't conn.setDefaultUseCaches(false); conn.setUseCaches(false); //------// conn.setConnectTimeout(Globals.CONNECT_TIMEOUT); conn.setReadTimeout(Globals.READ_TIMEOUT); conn.setRequestMethod(method); conn.setRequestProperty("Connection", "Keep-Alive"); if (requestProperties != null) { for (Map.Entry<String, String> prop : requestProperties.entrySet()) { conn.setRequestProperty(prop.getKey(), prop.getValue()); } } conn.setRequestProperty("User-Agent", Globals.applicationString()); if (method.equals("PUT")) { return conn; } else { int code = conn.getResponseCode(); if (log.isDebugEnabled()) { //logHeaders(conn); } // Redirects. These can occur even if followRedirects == true if there is a change in protocol, // for example http -> https. if (code >= 300 && code < 400) { if (redirectCount > MAX_REDIRECTS) { throw new IOException("Too many redirects"); } String newLocation = conn.getHeaderField("Location"); log.debug("Redirecting to " + newLocation); return openConnection(new URL(newLocation), requestProperties, method, redirectCount++); } // TODO -- handle other response codes. else if (code >= 400) { String message; if (code == 404) { message = "File not found: " + url.toString(); throw new FileNotFoundException(message); } else if (code == 401) { // Looks like this only happens when user hits "Cancel". // message = "Not authorized to view this file"; // JOptionPane.showMessageDialog(null, message, "HTTP error", JOptionPane.ERROR_MESSAGE); redirectCount = MAX_REDIRECTS + 1; return null; } else { message = conn.getResponseMessage(); } String details = readErrorStream(conn); log.error("URL: " + url.toExternalForm() + ". error stream: " + details); log.error("Code: " + code + ". " + message); HttpResponseException exc = new HttpResponseException(code); throw exc; } } return conn; }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImplClassifier.java
/** * Samples the URL passed in and stores the result in * <code>HTTPSampleResult</code>, following redirects and downloading page * resources as appropriate.//from ww w. j av a 2 s . co m * <p> * When getting a redirect target, redirects are not followed and resources * are not downloaded. The caller will take care of this. * * @param url * URL to sample * @param method * HTTP method: GET, POST,... * @param areFollowingRedirect * whether we're getting a redirect target * @param frameDepth * Depth of this target in the frame structure. Used only to * prevent infinite recursion. * @return results of the sampling */ protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { HttpURLConnection conn = null; String urlStr = url.toString(); log.debug("Start : sample " + urlStr); HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); res.setSampleLabel(urlStr); res.setURL(url); res.setHTTPMethod(method); res.sampleStart(); // Count the retries as well in the time // Check cache for an entry with an Expires header in the future final CacheManager cacheManager = getCacheManager(); if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) { if (cacheManager.inCache(url)) { res.sampleEnd(); res.setResponseNoContent(); res.setSuccessful(true); return res; } } try { // Sampling proper - establish the connection and read the response: // Repeatedly try to connect: int retry; // Start with 0 so tries at least once, and retries at most // MAX_CONN_RETRIES times for (retry = 0; retry <= MAX_CONN_RETRIES; retry++) { try { conn = setupConnection(url, method, res); // Attempt the connection: savedConn = conn; conn.connect(); break; } catch (BindException e) { if (retry >= MAX_CONN_RETRIES) { log.error("Can't connect after " + retry + " retries, " + e); throw e; } log.debug("Bind exception, try again"); if (conn != null) { savedConn = null; // we don't want interrupt to try // disconnection again conn.disconnect(); } setUseKeepAlive(false); continue; // try again } catch (IOException e) { log.debug("Connection failed, giving up"); throw e; } } if (retry > MAX_CONN_RETRIES) { // This should never happen, but... throw new BindException(); } // Nice, we've got a connection. Finish sending the request: if (method.equals(HTTPConstants.POST)) { String postBody = sendPostData(conn); res.setQueryString(postBody); } else if (method.equals(HTTPConstants.PUT)) { String putBody = sendPutData(conn); res.setQueryString(putBody); } // Request sent. Now get the response: byte[] responseData = readResponse(conn, res); res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setResponseData(responseData); @SuppressWarnings("null") // Cannot be null here int errorLevel = conn.getResponseCode(); String respMsg = conn.getResponseMessage(); String hdr = conn.getHeaderField(0); if (hdr == null) { hdr = "(null)"; // $NON-NLS-1$ } if (errorLevel == -1) {// Bug 38902 - sometimes -1 seems to be // returned unnecessarily if (respMsg != null) {// Bug 41902 - NPE try { errorLevel = Integer.parseInt(respMsg.substring(0, 3)); log.warn("ResponseCode==-1; parsed " + respMsg + " as " + errorLevel); } catch (NumberFormatException e) { log.warn("ResponseCode==-1; could not parse " + respMsg + " hdr: " + hdr); } } else { respMsg = hdr; // for result log.warn("ResponseCode==-1 & null ResponseMessage. Header(0)= " + hdr); } } if (errorLevel == -1) { res.setResponseCode("(null)"); // $NON-NLS-1$ } else { res.setResponseCode(Integer.toString(errorLevel)); } res.setSuccessful(isSuccessCode(errorLevel)); if (respMsg == null) {// has been seen in a redirect respMsg = hdr; // use header (if possible) if no message found } res.setResponseMessage(respMsg); String ct = conn.getContentType(); if (ct != null) { res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } String responseHeaders = getResponseHeaders(conn); res.setResponseHeaders(responseHeaders); if (res.isRedirect()) { res.setRedirectLocation(conn.getHeaderField(HTTPConstants.HEADER_LOCATION)); } // record headers size to allow HTTPSampleResult.getBytes() with // different options res.setHeadersSize(responseHeaders.replaceAll("\n", "\r\n") // $NON-NLS-1$ // $NON-NLS-2$ .length() + 2); // add 2 for a '\r\n' at end of headers // (before data) if (log.isDebugEnabled()) { log.debug("Response headersSize=" + res.getHeadersSize() + " bodySize=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { res.setURL(conn.getURL()); } // Store any cookies received in the cookie manager: saveConnectionCookies(conn, url, getCookieManager()); // Save cache information if (cacheManager != null) { cacheManager.saveDetails(conn, res); } res = resultProcessing(areFollowingRedirect, frameDepth, res); log.debug("End : sample"); return res; } catch (IOException e) { res.sampleEnd(); savedConn = null; // we don't want interrupt to try disconnection // again // We don't want to continue using this connection, even if // KeepAlive is set if (conn != null) { // May not exist conn.disconnect(); } conn = null; // Don't process again return errorResult(e, res); } finally { // calling disconnect doesn't close the connection immediately, // but indicates we're through with it. The JVM should close // it when necessary. savedConn = null; // we don't want interrupt to try disconnection // again disconnect(conn); // Disconnect unless using KeepAlive } }
From source file:com.BeatYourRecord.SubmitActivity.java
private String uploadMetaData(String filePath, boolean retry) throws IOException { String uploadUrl = INITIAL_UPLOAD_URL; HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true);/*from w ww. j a va 2 s . c o m*/ urlConnection.setRequestProperty("Content-Type", "application/atom+xml"); urlConnection.setRequestProperty("Slug", filePath); String atomData; int pos = filePath.indexOf("BYR"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd"); String currentDateandTime = sdf.format(new Date()); SharedPreferences pref1 = SubmitActivity.this.getSharedPreferences("TourPref", 0); // 0 - for private mode Editor editor1 = pref1.edit(); String username = pref1.getString("Username", null); String title = "BeatYourRecord Free Throws " + currentDateandTime + " Score : " + getTitleText() + " User : " + username; //this.initFile().getAbsolutePath(); String description = "Beat Your Record Free Throw Tournament. User : " + username + ". Go to" + " www.ec2-54-212-221-3.us-west-2.compute.amazonaws.com" + " to take part in our other tournaments"; String category = DEFAULT_VIDEO_CATEGORY; this.tags = DEFAULT_VIDEO_TAGS; if (!Util.isNullOrEmpty(this.getTagsText())) { this.tags = this.getTagsText(); } if (this.videoLocation == null) { String template = Util.readFile(this, R.raw.gdata).toString(); atomData = String.format(template, title, description, category, this.tags); } else { String template = Util.readFile(this, R.raw.gdata_geo).toString(); atomData = String.format(template, title, description, category, this.tags, videoLocation.getLatitude(), videoLocation.getLongitude()); } OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream()); outStreamWriter.write(atomData); outStreamWriter.close(); int responseCode = urlConnection.getResponseCode(); if (responseCode < 200 || responseCode >= 300) { // The response code is 40X if ((responseCode + "").startsWith("4") && retry) { Log.d(LOG_TAG, "retrying to fetch auth token for " + youTubeName); this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken); // Try again with fresh token return uploadMetaData(filePath, false); } else { throw new IOException(String.format("response code='%s' (code %d)" + " for %s", urlConnection.getResponseMessage(), responseCode, urlConnection.getURL())); } } return urlConnection.getHeaderField("Location"); }
From source file:com.google.ytd.SubmitActivity.java
private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException { int chunk = end - start + 1; int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; FileInputStream fileStream = new FileInputStream(file); HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); // some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem if (isFirstRequest()) { Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded)); urlConnection.setRequestMethod("POST"); } else {/* w w w.j a v a2 s.c o m*/ urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.", (int) totalBytesUploaded)); } urlConnection.setDoOutput(true); urlConnection.setFixedLengthStreamingMode(chunk); urlConnection.setRequestProperty("Content-Type", "video/3gpp"); urlConnection.setRequestProperty("Content-Range", String.format("bytes %d-%d/%d", start, end, file.length())); Log.d(LOG_TAG, urlConnection.getRequestProperty("Content-Range")); OutputStream outStreamWriter = urlConnection.getOutputStream(); fileStream.skip(start); int bytesRead; int totalRead = 0; while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) { outStreamWriter.write(buffer, 0, bytesRead); totalRead += bytesRead; this.totalBytesUploaded += bytesRead; double percent = (totalBytesUploaded / currentFileSize) * 99; /* Log.d(LOG_TAG, String.format( "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize, totalBytesUploaded, percent)); */ dialog.setProgress((int) percent); if (totalRead == (end - start + 1)) { break; } } outStreamWriter.close(); int responseCode = urlConnection.getResponseCode(); Log.d(LOG_TAG, "responseCode=" + responseCode); Log.d(LOG_TAG, "responseMessage=" + urlConnection.getResponseMessage()); try { if (responseCode == 201) { String videoId = parseVideoId(urlConnection.getInputStream()); String latLng = null; if (this.videoLocation != null) { latLng = String.format("lat=%f lng=%f", this.videoLocation.getLatitude(), this.videoLocation.getLongitude()); } submitToYtdDomain(this.ytdDomain, this.assignmentId, videoId, this.youTubeName, SubmitActivity.this.clientLoginToken, getTitleText(), getDescriptionText(), this.dateTaken, latLng, this.tags); dialog.setProgress(100); return videoId; } else if (responseCode == 200) { Set<String> keySet = urlConnection.getHeaderFields().keySet(); String keys = urlConnection.getHeaderFields().keySet().toString(); Log.d(LOG_TAG, String.format("Headers keys %s.", keys)); for (String key : keySet) { Log.d(LOG_TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key))); } Log.w(LOG_TAG, "Received 200 response during resumable uploading"); throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { if ((responseCode + "").startsWith("5")) { String error = String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage()); Log.w(LOG_TAG, error); // TODO - this exception will trigger retry mechanism to kick in // TODO - even though it should not, consider introducing a new type so // TODO - resume does not kick in upon 5xx throw new IOException(error); } else if (responseCode == 308) { // OK, the chunk completed succesfully Log.d(LOG_TAG, String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { // TODO - this case is not handled properly yet Log.w(LOG_TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode, urlConnection.getResponseMessage(), uploadUrl)); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; }
From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException { int chunk = end - start + 1; int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; FileInputStream fileStream = new FileInputStream(file); HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); // some mobile proxies do not support PUT, using X-HTTP-Method-Override // to get around this problem if (isFirstRequest()) { Log.d(TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded)); urlConnection.setRequestMethod("POST"); } else {//from w w w. ja va 2 s . c o m urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); Log.d(TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.", (int) totalBytesUploaded)); } urlConnection.setDoOutput(true); urlConnection.setFixedLengthStreamingMode(chunk); // /XXX hardcoded video mimetype urlConnection.setRequestProperty("Content-Type", "video/mp4"); urlConnection.setRequestProperty("Content-Range", String.format("bytes %d-%d/%d", start, end, file.length())); Log.d(TAG, urlConnection.getRequestProperty("Content-Range")); OutputStream outStreamWriter = urlConnection.getOutputStream(); fileStream.skip(start); int bytesRead; int totalRead = 0; while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) { outStreamWriter.write(buffer, 0, bytesRead); totalRead += bytesRead; this.totalBytesUploaded += bytesRead; // double percent = (totalBytesUploaded / currentFileSize) * 99; /* * Log.d(TAG, String.format( * "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize, * totalBytesUploaded, percent)); */ if (totalRead == (end - start + 1)) { break; } } outStreamWriter.close(); int responseCode = urlConnection.getResponseCode(); Log.d(TAG, "responseCode=" + responseCode); Log.d(TAG, "responseMessage=" + urlConnection.getResponseMessage()); try { if (responseCode == 201) { String videoId = parseVideoId(urlConnection.getInputStream()); Log.i(TAG, "Youtube video submitted - new video id is " + videoId); // 100% finished here. // dialog.setProgress(100); return videoId; } else if (responseCode == 200) { Set<String> keySet = urlConnection.getHeaderFields().keySet(); String keys = urlConnection.getHeaderFields().keySet().toString(); Log.d(TAG, String.format("Headers keys %s.", keys)); for (String key : keySet) { Log.d(TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key))); } Log.w(TAG, "Received 200 response during resumable uploading"); throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { if ((responseCode + "").startsWith("5")) { String error = String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage()); Log.w(TAG, error); // TODO - this exception will trigger retry mechanism to // kick in // TODO - even though it should not, consider introducing a // new type so // TODO - resume does not kick in upon 5xx throw new IOException(error); } else if (responseCode == 308) { // OK, the chunk completed successfully Log.d(TAG, String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { // TODO - this case is not handled properly yet Log.w(TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode, urlConnection.getResponseMessage(), uploadUrl)); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; }
From source file:org.openymsg.network.Session.java
private void saveFT(final SessionFileTransferEvent ev, final String path, String filename) throws FileTransferFailedException, IOException { int len;//from www . j ava2 s.c om byte[] buff = new byte[4096]; // HTTP request HttpURLConnection uConn = (HttpURLConnection) (ev.getLocation().openConnection()); Util.initURLConnection(uConn); uConn.setRequestProperty("User-Agent", NetworkConstants.USER_AGENT); // uConn.setRequestProperty("Host",ftHost); uConn.setRequestProperty("Cookie", this.cookieY + "; " + this.cookieT); uConn.connect(); // Response header if (uConn.getResponseCode() != 200) throw new FileTransferFailedException("Server HTTP error code: " + uConn.getResponseCode()); String rp = uConn.getHeaderField("Content-Disposition"); if (path != null && rp != null) { int i = rp.indexOf("filename="); if (i >= 0) filename = rp.substring(i + 9); // Strip quotes if necessary if (filename.charAt(0) == '\"') filename = filename.substring(1, filename.length() - 1); } // Response body if (path != null) filename = path + filename; InputStream is = uConn.getInputStream(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filename)); try { do { len = is.read(buff); if (len > 0) bos.write(buff, 0, len); } while (len >= 0); bos.flush(); } finally { bos.close(); is.close(); } uConn.disconnect(); }