List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:at.spardat.xma.boot.transport.HTTPTransport.java
private byte[] callServerEventImpl(IRtXMASessionClient session, URL url, byte[] input, boolean handleRedirect) throws CommunicationException { OutputStream serverIn;/*from ww w .j a v a 2 s. c o m*/ int code = 0; HttpURLConnection conn; byte[] buffer = null; try { conn = (HttpURLConnection) url.openConnection(); if (conn instanceof HttpsURLConnection) { ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier); } conn.setDoOutput(true); conn.setRequestMethod("POST"); //$NON-NLS-1$ sendCookies(session, url, conn); conn.setRequestProperty(Statics.HTTP_CONTENT_TYPE, "application/octet-stream"); //$NON-NLS-1$ conn.setRequestProperty(Statics.HTTP_ACCEPT, "application/octet-stream"); //$NON-NLS-1$ conn.setRequestProperty(Statics.HTTP_USER_AGENT, Statics.HTTP_USER_AGENT_NAME); serverIn = conn.getOutputStream(); } catch (IOException exc) { log_.log(LogLevel.WARNING, "error calling '" + url.toString() + "' at the server:", exc); //$NON-NLS-1$ throw new ConnectException("error calling '" + url.toString() + "' at the server:", exc); } try { serverIn.write(input); serverIn.close(); code = conn.getResponseCode(); // if requested, we allow redirect also on POST requests, therewith violating RFC 2616 section 10.3! if (handleRedirect && 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); } buffer = this.readOutput(conn); readCookies(session, url, conn); return buffer; } 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 calling '" + url.toString() + "' at 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 calling '" + url.toString() + "' at the server:", ex); //$NON-NLS-1$ if (code < 500) throw new ConnectException("error calling '" + url.toString() + "' at the server:", ex); else throw new ServerException("error calling '" + url.toString() + "' at the server:", ex); } }
From source file:org.sakaiproject.content.chh.dspace.ContentHostingHandlerImplDSpace.java
public void commit(ContentResourceEdit edit) { ContentResourceDSpace crds = null;//w w w .j a v a2 s .c o m if (edit instanceof ContentResourceDSpace) crds = (ContentResourceDSpace) edit; else { ContentEntity tmp = edit.getVirtualContentEntity(); if (tmp instanceof ContentResourceDSpace) crds = (ContentResourceDSpace) tmp; } if (crds == null) return; // can't do anything if the resource isn't a // dspace resource! ContentEntityDSpace encloser = resolveDSpace(crds.realParent, crds.endpoint, crds.basehandle, crds.parentRelativePath, crds.chh, crds.searchable); if (encloser == null || encloser.dii == null || encloser.dii.handle == null) { log.warn( "Content Hosting Handler DSpace was unable to save the contents of a resource because the enclosing collection was not found."); return; // parent collection has been erased } // encloser.dii.handle is the parent collection handle to which we // http/dav PUT this resource InputStream is = null; OutputStream os = null; try { is = edit.streamContent(); if (is == null) return; // abort the commit if we can't stream it // through byte b[] = new byte[1024]; String puturl = crds.dii.endpoint; puturl = puturl.substring(0, puturl.lastIndexOf("/")); puturl = puturl + "/dso_" + encloser.dii.handle.replace("/", "%24") + "?package=PDF"; URL url = new URL(puturl); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setRequestMethod("PUT"); huc.setRequestProperty("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"); huc.setRequestProperty("User-Agent", "Axis/1.3"); huc.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); huc.setRequestProperty("Content-Length", "" + is.available()); huc.setRequestProperty("Authorization", "Basic am9obmYlNDBjYXJldC5jYW0uYWMudWs6cGFzc3dvcmQ="); huc.setDoInput(true); huc.setDoOutput(true); huc.connect(); os = huc.getOutputStream(); while (is.available() > 0) { int l = is.read(b); if (l > 0) os.write(b, 0, l); else break; } os.flush(); is.close(); huc.getResponseCode(); String handleInsideJunk = huc.getHeaderField("Location"); if (handleInsideJunk == null) return; crds.dii.handle = handleInsideJunk .substring(5/* skip the /dso_ prefix */ + handleInsideJunk.lastIndexOf("/")) .replace("%24", "/"); } catch (IOException e) { log.warn( "Content Hosting Handler DSpace was unable to save the contents of a resource because DSpace refused the operation.", e); return; // file system error -- operation cannot be performed } catch (SecurityException e) { log.warn( "Content Hosting Handler DSpace was unable to save the contents of a resource because the JVM SecurityManager refused the operation.", e); return; // permissions error -- operation cannot be performed } catch (ServerOverloadException e) { log.warn( "Content Hosting Handler DSpace was unable to save the contents of a resource because the server threw a ServerOverloadException and was unable to stream the resource contents.", e); return; // sakai failed to deliver the contents of the file; saving // it is obviously impossible } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (os != null) try { os.flush(); os.close(); } catch (IOException e) { } } checkForUnmountRequest(edit); }
From source file:org.apache.ambari.server.controller.internal.URLStreamProvider.java
/** * Get a URL connection from the given spec. * * @param spec the String to parse as a URL * @param requestMethod the HTTP method (GET,POST,PUT,etc.). * @param params the body of the request; may be null * @param headers the headers of the request; may be null * * @return a URL connection/*from ww w . j a v a2 s . c o m*/ * * @throws IOException if the URL connection can not be established */ public HttpURLConnection processURL(String spec, String requestMethod, Object params, Map<String, List<String>> headers) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("readFrom spec:" + spec); } HttpURLConnection connection = spec.startsWith("https") ? getSSLConnection(spec) : getConnection(spec); AppCookieManager appCookieManager = getAppCookieManager(); String appCookie = appCookieManager.getCachedAppCookie(spec); if (appCookie != null) { LOG.debug("Using cached app cookie for URL:" + spec); // allow for additional passed in cookies if (headers == null || headers.isEmpty()) { headers = Collections.singletonMap(COOKIE, Collections.singletonList(appCookie)); } else { headers = new HashMap<String, List<String>>(headers); List<String> cookieList = headers.get(COOKIE); String cookies = cookieList.isEmpty() ? null : cookieList.get(0); headers.put(COOKIE, Collections.singletonList(appendCookie(cookies, appCookie))); } } connection.setConnectTimeout(connTimeout); connection.setReadTimeout(readTimeout); connection.setDoOutput(true); connection.setRequestMethod(requestMethod); if (headers != null) { for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String paramValue = entry.getValue().toString(); connection.setRequestProperty(entry.getKey(), paramValue.substring(1, paramValue.length() - 1)); } } if (params != null) { byte[] info; if (params instanceof InputStream) { info = IOUtils.toByteArray((InputStream) params); } else { info = ((String) params).getBytes(); } connection.getOutputStream().write(info); } int statusCode = connection.getResponseCode(); if (statusCode == HttpStatus.SC_UNAUTHORIZED) { String wwwAuthHeader = connection.getHeaderField(WWW_AUTHENTICATE); if (LOG.isInfoEnabled()) { LOG.info("Received WWW-Authentication header:" + wwwAuthHeader + ", for URL:" + spec); } if (wwwAuthHeader != null && wwwAuthHeader.trim().startsWith(NEGOTIATE)) { connection = spec.startsWith("https") ? getSSLConnection(spec) : getConnection(spec); appCookie = appCookieManager.getAppCookie(spec, true); connection.setRequestProperty(COOKIE, appCookie); connection.setConnectTimeout(connTimeout); connection.setReadTimeout(readTimeout); connection.setDoOutput(true); return connection; } else { // no supported authentication type found // we would let the original response propogate LOG.error("Unsupported WWW-Authentication header:" + wwwAuthHeader + ", for URL:" + spec); return connection; } } else { // not a 401 Unauthorized status code // we would let the original response propogate return connection; } }
From source file:org.oclc.oai.harvester.verb.HarvesterVerb.java
/** * Performs the OAI request//from ww w .j a va 2 s . co m * * @param requestURL * @throws IOException * @throws ParserConfigurationException * @throws SAXException * @throws TransformerException */ public void harvestOldOclcImplementation(String requestURL) throws IOException, ParserConfigurationException, SAXException, TransformerException { this.requestURL = requestURL; logger.debug("requestURL=" + requestURL); InputStream in; URL url = new URL(requestURL); HttpURLConnection con; int responseCode; do { con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("User-Agent", "OAIHarvester/2.0"); con.setRequestProperty("Accept-Encoding", "compress, gzip, identify"); try { responseCode = con.getResponseCode(); logger.debug("responseCode=" + responseCode); } catch (FileNotFoundException e) { // assume it's a 503 response logger.error(requestURL, e); responseCode = HttpURLConnection.HTTP_UNAVAILABLE; } if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) { long retrySeconds = con.getHeaderFieldInt("Retry-After", -1); if (retrySeconds == -1) { long now = (new Date()).getTime(); long retryDate = con.getHeaderFieldDate("Retry-After", now); retrySeconds = retryDate - now; } if (retrySeconds == 0) { // Apparently, it's a bad URL throw new FileNotFoundException("Bad URL?"); } logger.warn("Server response: Retry-After=" + retrySeconds); if (retrySeconds > 0) { try { Thread.sleep(retrySeconds * 1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } while (responseCode == HttpURLConnection.HTTP_UNAVAILABLE); String contentEncoding = con.getHeaderField("Content-Encoding"); logger.debug("contentEncoding=" + contentEncoding); if ("compress".equals(contentEncoding)) { ZipInputStream zis = new ZipInputStream(con.getInputStream()); zis.getNextEntry(); in = zis; } else if ("gzip".equals(contentEncoding)) { in = new GZIPInputStream(con.getInputStream()); } else if ("deflate".equals(contentEncoding)) { in = new InflaterInputStream(con.getInputStream()); } else { in = con.getInputStream(); } InputSource data = new InputSource(in); Thread t = Thread.currentThread(); DocumentBuilder builder = builderMap.get(t); if (builder == null) { builder = factory.newDocumentBuilder(); builderMap.put(t, builder); } doc = builder.parse(data); StringTokenizer tokenizer = new StringTokenizer(getSingleString("/*/@xsi:schemaLocation"), " "); StringBuffer sb = new StringBuffer(); while (tokenizer.hasMoreTokens()) { if (sb.length() > 0) sb.append(" "); sb.append(tokenizer.nextToken()); } this.schemaLocation = sb.toString(); }
From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
private ResumeInfo resumeFileUpload(String uploadUrl) throws IOException, ParserConfigurationException, SAXException, Internal500ResumeException { HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestProperty("Content-Range", "bytes */*"); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); urlConnection.setFixedLengthStreamingMode(0); HttpURLConnection.setFollowRedirects(false); urlConnection.connect();// w w w . ja v a 2s . co m int responseCode = urlConnection.getResponseCode(); if (responseCode >= 300 && responseCode < 400) { int nextByteToUpload; String range = urlConnection.getHeaderField("Range"); if (range == null) { Log.d(TAG, String.format("PUT to %s did not return 'Range' header.", uploadUrl)); nextByteToUpload = 0; } else { Log.d(TAG, String.format("Range header is '%s'.", range)); String[] parts = range.split("-"); if (parts.length > 1) { nextByteToUpload = Integer.parseInt(parts[1]) + 1; } else { nextByteToUpload = 0; } } return new ResumeInfo(nextByteToUpload); } else if (responseCode >= 200 && responseCode < 300) { return new ResumeInfo(parseVideoId(urlConnection.getInputStream())); } else if (responseCode == 500) { // TODO this is a workaround for current problems with resuming // uploads while switching transport (Wifi->EDGE) throw new Internal500ResumeException( String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl, urlConnection.getResponseMessage(), responseCode)); } else { throw new IOException(String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl, urlConnection.getResponseMessage(), responseCode)); } }
From source file:org.shredzone.flattr4j.connector.impl.FlattrConnection.java
@Override public Collection<FlattrObject> result() throws FlattrException { try {//from ww w.j a va2 s.c om String queryString = (queryParams != null ? "?" + queryParams : ""); URL url; if (call != null) { url = new URI(baseUrl).resolve(call + queryString).toURL(); } else { url = new URI(baseUrl + queryString).toURL(); } HttpURLConnection conn = createConnection(url); conn.setRequestMethod(type.name()); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Accept-Charset", ENCODING); conn.setRequestProperty("Accept-Encoding", "gzip"); if (token != null) { conn.setRequestProperty("Authorization", "Bearer " + token.getToken()); } else if (key != null) { conn.setRequestProperty("Authorization", "Basic " + base64(key.getKey() + ':' + key.getSecret())); } byte[] outputData = null; if (data != null) { outputData = data.toString().getBytes(ENCODING); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setFixedLengthStreamingMode(outputData.length); } else if (formParams != null) { outputData = formParams.toString().getBytes(ENCODING); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setFixedLengthStreamingMode(outputData.length); } LOG.info("Sending Flattr request: {0}", call); conn.connect(); if (outputData != null) { OutputStream out = conn.getOutputStream(); try { out.write(outputData); } finally { out.close(); } } if (limit != null) { String remainingHeader = conn.getHeaderField("X-RateLimit-Remaining"); if (remainingHeader != null) { limit.setRemaining(Long.parseLong(remainingHeader)); } else { limit.setRemaining(null); } String limitHeader = conn.getHeaderField("X-RateLimit-Limit"); if (limitHeader != null) { limit.setLimit(Long.parseLong(limitHeader)); } else { limit.setLimit(null); } String currentHeader = conn.getHeaderField("X-RateLimit-Current"); if (currentHeader != null) { limit.setCurrent(Long.parseLong(currentHeader)); } else { limit.setCurrent(null); } String resetHeader = conn.getHeaderField("X-RateLimit-Reset"); if (resetHeader != null) { limit.setReset(new Date(Long.parseLong(resetHeader) * 1000L)); } else { limit.setReset(null); } } List<FlattrObject> result; if (assertStatusOk(conn)) { // Status is OK and there is content Object resultData = new JSONTokener(readResponse(conn)).nextValue(); if (resultData instanceof JSONArray) { JSONArray array = (JSONArray) resultData; result = new ArrayList<FlattrObject>(array.length()); for (int ix = 0; ix < array.length(); ix++) { FlattrObject fo = new FlattrObject(array.getJSONObject(ix)); result.add(fo); LOG.verbose("<- JSON result: {0}", fo); } LOG.verbose("<- {0} rows", array.length()); } else if (resultData instanceof JSONObject) { FlattrObject fo = new FlattrObject((JSONObject) resultData); result = Collections.singletonList(fo); LOG.verbose("<- JSON result: {0}", fo); } else { throw new MarshalException("unexpected result type " + resultData.getClass().getName()); } } else { // Status was OK, but there is no content result = Collections.emptyList(); } return result; } catch (URISyntaxException ex) { throw new IllegalStateException("bad baseUrl"); } catch (IOException ex) { throw new FlattrException("API access failed: " + call, ex); } catch (JSONException ex) { throw new MarshalException(ex); } catch (ClassCastException ex) { throw new FlattrException("Unexpected result type", ex); } }
From source file:tree.love.providers.downloads.DownloadThread.java
/** * Fully execute a single download request. Setup and send the request, * handle the response, and transfer the data to the destination file. *///w w w.ja va 2 s . c o m private void executeDownload(State state) throws StopRequestException { state.resetBeforeExecute(); setupDestinationFile(state); // skip when already finished; remove after fixing race in 5217390 if (state.mCurrentBytes == state.mTotalBytes) { Log.i(Constants.TAG, "Skipping initiating request for download " + mInfo.mId + "; already completed"); return; } while (state.mRedirectionCount++ < Constants.MAX_REDIRECTS) { // Open connection and follow any redirects until we have a useful // response with body. HttpURLConnection conn = null; try { checkConnectivity(); conn = (HttpURLConnection) state.mUrl.openConnection(); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(DEFAULT_TIMEOUT); conn.setReadTimeout(DEFAULT_TIMEOUT); addRequestHeaders(state, conn); final int responseCode = conn.getResponseCode(); switch (responseCode) { case HTTP_OK: if (state.mContinuingDownload) { throw new StopRequestException(STATUS_CANNOT_RESUME, "Expected partial, but received OK"); } processResponseHeaders(state, conn); transferData(state, conn); return; case HTTP_PARTIAL: if (!state.mContinuingDownload) { throw new StopRequestException(STATUS_CANNOT_RESUME, "Expected OK, but received partial"); } transferData(state, conn); return; case HTTP_MOVED_PERM: case HTTP_MOVED_TEMP: case HTTP_SEE_OTHER: case HTTP_TEMP_REDIRECT: final String location = conn.getHeaderField("Location"); state.mUrl = new URL(state.mUrl, location); if (responseCode == HTTP_MOVED_PERM) { // Push updated URL back to database state.mRequestUri = state.mUrl.toString(); } continue; case HTTP_REQUESTED_RANGE_NOT_SATISFIABLE: throw new StopRequestException(STATUS_CANNOT_RESUME, "Requested range not satisfiable"); case HTTP_UNAVAILABLE: parseRetryAfterHeaders(state, conn); throw new StopRequestException(HTTP_UNAVAILABLE, conn.getResponseMessage()); case HTTP_INTERNAL_ERROR: throw new StopRequestException(HTTP_INTERNAL_ERROR, conn.getResponseMessage()); default: StopRequestException.throwUnhandledHttpError(responseCode, conn.getResponseMessage()); } } catch (IOException e) { // Trouble with low-level sockets throw new StopRequestException(STATUS_HTTP_DATA_ERROR, e); } finally { if (conn != null) conn.disconnect(); } } throw new StopRequestException(STATUS_TOO_MANY_REDIRECTS, "Too many redirects"); }
From source file:com.juick.android.Utils.java
public static RESTResponse postForm(final Context context, final String url, ArrayList<NameValuePair> data) { try {// w w w. ja v a2 s .co m final String end = "\r\n"; final String twoHyphens = "--"; final String boundary = "****+++++******+++++++********"; URL apiUrl = new URL(url); final HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection(); conn.setConnectTimeout(10000); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.connect(); OutputStream out = conn.getOutputStream(); PrintStream ps = new PrintStream(out); int index = 0; byte[] block = new byte[1024]; for (NameValuePair nameValuePair : data) { ps.print(twoHyphens + boundary + end); ps.print("Content-Disposition: form-data; name=\"" + nameValuePair.getName() + "\"" + end + end); final InputStream value = nameValuePair.getValue(); while (true) { final int rd = value.read(block, 0, block.length); if (rd < 1) { break; } ps.write(block, 0, rd); } value.close(); ps.print(end); } ps.print(twoHyphens + boundary + twoHyphens + end); ps.close(); boolean b = conn.getResponseCode() == 200; if (!b) { return new RESTResponse("HTTP " + conn.getResponseCode() + ": " + conn.getResponseMessage(), false, null); } else { InputStream inputStream = conn.getInputStream(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] arr = new byte[1024]; while (true) { int rd = inputStream.read(arr); if (rd < 1) break; baos.write(arr, 0, rd); } if (conn.getHeaderField("X-GZIPCompress") != null) { return new RESTResponse(null, false, baos.toString(0)); } else { return new RESTResponse(null, false, baos.toString()); } } finally { inputStream.close(); } } } catch (IOException e) { return new RESTResponse(e.toString(), false, null); } }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
protected byte[] sendCmpHttp(byte[] message, int httpRespCode, String cmpAlias) throws IOException { // POST the CMP request // we are going to do a POST final String urlString = getProperty("httpCmpProxyURL", this.httpReqPath + '/' + resourceCmp) + '/' + cmpAlias;// w w w. j a v a 2s . com log.info("http URL: " + urlString); URL url = new URL(urlString); final HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/pkixcmp"); con.connect(); // POST it OutputStream os = con.getOutputStream(); os.write(message); os.close(); assertEquals("Unexpected HTTP response code.", httpRespCode, con.getResponseCode()); // Only try to read the response if we expected a 200 (ok) response if (httpRespCode != 200) { return null; } // Some appserver (Weblogic) responds with // "application/pkixcmp; charset=UTF-8" assertNotNull("No content type in response.", con.getContentType()); assertTrue(con.getContentType().startsWith("application/pkixcmp")); // Check that the CMP respone has the cache-control headers as specified in // http://tools.ietf.org/html/draft-ietf-pkix-cmp-transport-protocols-14 final String cacheControl = con.getHeaderField("Cache-Control"); assertNotNull("'Cache-Control' header is not present.", cacheControl); assertEquals("no-cache", cacheControl); final String pragma = con.getHeaderField("Pragma"); assertNotNull(pragma); assertEquals("no-cache", pragma); // Now read in the bytes ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and CMP requests are small enough InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); assertNotNull(respBytes); assertTrue(respBytes.length > 0); return respBytes; }
From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java
@Override protected Integer doInBackground(Void... params) { SharedPreferences prefs = dataService.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE); // Connectivity receiver. final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); ComponentName receiver = new ComponentName(dataService, WifiReceiver.class); PackageManager pm = dataService.getPackageManager(); if (activeNetwork == null || !activeNetwork.isConnected()) { // We've missed a scheduled update. Enable the receiver so it can launch an update when we reconnect. Log.d(LOG_TAG, "Missed library update: not connected. Enabling connectivity receiver."); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); return RESULT_CODE_FAILURE; } else {/*from w w w . ja v a 2s.c o m*/ // We are connected. Disable the receiver. Log.d(LOG_TAG, "Library updater connected. Disabling connectivity receiver."); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } InputStream in = null; String etag = prefs.getString(SETTING_LIBRARY_ETAG, null); try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); if (etag != null && !force) { conn.setRequestProperty("If-None-Match", etag); } int code = conn.getResponseCode(); switch (code) { case HttpStatus.SC_NOT_MODIFIED: // If we got a 304, we're done. // Use failure code to indicate there is no temp db to copy over. Log.d(LOG_TAG, "304 in library response."); return RESULT_CODE_FAILURE; default: // Odd, but on 1/3/13 I received correct json responses with a -1 for responseCode. Fall through. Log.w(LOG_TAG, "Error code in library response: " + code); case HttpStatus.SC_OK: // Parse response. in = conn.getInputStream(); JsonFactory factory = new JsonFactory(); final JsonParser parser = factory.createJsonParser(in); SQLiteDatabase tempDb = tempDbHelper.getWritableDatabase(); tempDb.beginTransaction(); try { tempDb.execSQL("delete from topic"); tempDb.execSQL("delete from topicvideo"); tempDb.execSQL("delete from video"); parseObject(parser, tempDb, null, 0); tempDb.setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); return RESULT_CODE_FAILURE; } finally { tempDb.endTransaction(); tempDb.close(); } // Save etag once we've successfully parsed the response. etag = conn.getHeaderField("ETag"); prefs.edit().putString(SETTING_LIBRARY_ETAG, etag).apply(); // Move this new content from the temp db into the main one. mergeDbs(); return RESULT_CODE_SUCCESS; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (JsonParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { tempDbHelper.close(); } return RESULT_CODE_FAILURE; }