List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:org.apache.olingo.fit.tecsvc.http.DerivedAndMixedTypeTestITCase.java
@Test public void queryESTwoPrimWithEntityTypeCast() throws Exception { URL url = new URL(SERVICE_URI + "ESTwoPrim(111)/olingo.odata.test1.ETBase"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=full"); connection.connect();//from w ww. ja v a 2 s . co m assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.JSON_FULL_METADATA, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE))); final String content = IOUtils.toString(connection.getInputStream()); assertTrue(content .contains("\"@odata.type\":\"#olingo.odata.test1.ETBase\"," + "\"@odata.id\":\"ESBase(111)\"," + "\"PropertyInt16@odata.type\":\"#Int16\"," + "\"PropertyInt16\":111," + "\"PropertyString\":\"TEST A\"," + "\"AdditionalPropertyString_5\":\"TEST A 0815\"")); }
From source file:org.apache.olingo.fit.tecsvc.http.DerivedAndMixedTypeTestITCase.java
@Test public void queryESCompCollDerivedJsonNone() throws Exception { URL url = new URL(SERVICE_URI + "ESCompCollDerived"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=none"); connection.connect();/*from www .j av a 2s. c o m*/ assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.JSON_NO_METADATA, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE))); final String content = IOUtils.toString(connection.getInputStream()); assertTrue(content.contains( "[{\"PropertyInt16\":32767,\"PropertyCompAno\":null,\"CollPropertyCompAno\":[{\"PropertyString\":" + "\"TEST9876\"}]},{\"PropertyInt16\":12345,\"PropertyCompAno\":{" + "\"PropertyString\":\"Num111\",\"AdditionalPropString\":" + "\"Test123\"},\"CollPropertyCompAno\":[{" + "\"PropertyString\":\"TEST12345\",\"AdditionalPropString\":\"Additional12345\"}," + "{\"PropertyString\":\"TESTabcd\"}]}]}")); }
From source file:com.qweex.callisto.podcast.DownloadTask.java
@Override protected Boolean doInBackground(String... params) { String TAG = StaticBlob.TAG(); boolean isVideo; Cursor current;/*from ww w . j a va 2 s .c om*/ long id = 0, identity = 0; Log.e(TAG, "Preparing to start: " + StaticBlob.databaseConnector.getActiveDownloads().getCount() + " downloads"); boolean canceled = false; while (StaticBlob.databaseConnector.getActiveDownloads().getCount() > 0) { if (isCancelled()) //Checks to see if it has been canceled by somewhere else { mNotificationManager.cancel(NOTIFICATION_ID); return false; } try { Cursor c = StaticBlob.databaseConnector.getActiveDownloads(); c.moveToFirst(); id = c.getLong(c.getColumnIndex("_id")); identity = c.getLong(c.getColumnIndex("identity")); isVideo = c.getInt(c.getColumnIndex("video")) > 0; current = StaticBlob.databaseConnector.getOneEpisode(identity); current.moveToFirst(); //Get info AudLink = current.getString(current.getColumnIndex("mp3link")); VidLink = current.getString(current.getColumnIndex("vidlink")); AudSize = current.getLong(current.getColumnIndex("mp3size")); VidSize = current.getLong(current.getColumnIndex("vidsize")); Title = current.getString(current.getColumnIndex("title")); Date = current.getString(current.getColumnIndex("date")); Show = current.getString(current.getColumnIndex("show")); Date = StaticBlob.sdfFile.format(StaticBlob.sdfRaw.parse(Date)); //Getting target Target = new File(StaticBlob.storage_path + File.separator + Show); Target.mkdirs(); if (Title.indexOf("|") > 0) Title = Title.substring(0, Title.indexOf("|")); Title = Title.trim(); AudFile = new File(Target, Date + "__" + StaticBlob.makeFileFriendly(Title) + EpisodeDesc.getExtension(AudLink)); if (VidLink != null) VidFile = new File(Target, Date + "__" + StaticBlob.makeFileFriendly(Title) + EpisodeDesc.getExtension(VidLink)); Target = isVideo ? VidFile : AudFile; //Prepare the HTTP Log.i(TAG, "Path: " + Target.getPath()); URL url = new URL(isVideo ? VidLink : AudLink); Log.i(TAG, "Starting download: " + url.toString()); Log.i(TAG, "Opening the connection..."); HttpURLConnection ucon = (HttpURLConnection) url.openConnection(); String lastModified = ucon.getHeaderField("Last-Modified"); ucon = (HttpURLConnection) url.openConnection(); if (Target.exists()) { ucon.setRequestProperty("Range", "bytes=" + Target.length() + "-"); ucon.setRequestProperty("If-Range", lastModified); } ucon.setReadTimeout(TIMEOUT_CONNECTION); ucon.setConnectTimeout(TIMEOUT_SOCKET); ucon.connect(); //Notification mBuilder.setProgress(100, 0, true) .setContentTitle(this.context.getResources().getString(R.string.downloading) + " " + StaticBlob.current_download + " " + this.context.getResources().getString(R.string.of) + " " + downloading_count) .setContentText(Show + ": " + Title); // Displays the progress bar for the first time. mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); //Actually do the DLing InputStream is = ucon.getInputStream(); TotalSize = ucon.getContentLength() + Target.length(); BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5); FileOutputStream outStream; byte buff[]; Log.i(TAG, "mmk skipping the downloaded portion..." + Target.length() + " of " + TotalSize); if (Target.exists()) //Append if it exists outStream = new FileOutputStream(Target, true); else outStream = new FileOutputStream(Target); buff = new byte[5 * 1024]; Log.i(TAG, "Getting content length (size)"); int len = 0; long downloadedSize = Target.length(), percentDone = 0; //SPEED_COUNT == the number of times through the buffer loop to go through before updating the speed // currentDownloadLoopIndex == ??? // lastTime == The time that the last speed was calculated at // all_spds == All speeds tabulated thus far from currentDownloadLoopIndex to SPEED_COUNT // avg_speed == the average speed when SPEED_COUNT is reached int SPEED_COUNT = 200, currentDownloadLoopIndex = 0; long lastTime = (new java.util.Date()).getTime(), all_spds = 0; double avg_speed = 0; DecimalFormat df = new DecimalFormat("#.##"); //Wifi lock WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (DownloadList.Download_wifiLock == null) DownloadList.Download_wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, "Callisto_download"); if (!DownloadList.Download_wifiLock.isHeld()) DownloadList.Download_wifiLock.acquire(); Log.i(TAG, "FINALLY starting the download"); inner_failures = 0; //-----------------Here is where the actual downloading happens---------------- while (len != -1) { Cursor active = StaticBlob.databaseConnector.getActiveDownloads(); if (StaticBlob.databaseConnector.getActiveDownloads().getCount() == 0) canceled = true; else { active.moveToFirst(); canceled = active.getLong(active.getColumnIndex("identity")) != identity; } if (canceled) { Log.i(TAG, "Download has been canceled, deleting."); Target.delete(); break; } if (isCancelled()) { mNotificationManager.cancel(NOTIFICATION_ID); return false; } try { len = inStream.read(buff); if (len == -1) break; outStream.write(buff, 0, len); downloadedSize += len; percentDone = downloadedSize * 100; percentDone /= TotalSize; //Add to the average speed long temp_spd = 0; long time_diff = ((new java.util.Date()).getTime() - lastTime); if (time_diff > 0) { temp_spd = len * 100 / time_diff; currentDownloadLoopIndex++; all_spds += temp_spd; lastTime = (new java.util.Date()).getTime(); } } catch (IOException e) { Log.e(TAG + ":IOException", "IO is a moon - " + inner_failures); inner_failures++; if (inner_failures == INNER_LIMIT) break; try { Thread.sleep(500); } catch (InterruptedException e1) { } //Add failure to average currentDownloadLoopIndex++; lastTime = (new java.util.Date()).getTime(); } catch (Exception e) { Log.e(TAG + ":??Exception", e.getClass() + " : " + e.getMessage()); try { Thread.sleep(500); } catch (InterruptedException e1) { } //Add failure to average currentDownloadLoopIndex++; lastTime = (new java.util.Date()).getTime(); } //If the time is right, get the average if (currentDownloadLoopIndex >= SPEED_COUNT) { avg_speed = all_spds * 1.0 / currentDownloadLoopIndex / 100; all_spds = 0; currentDownloadLoopIndex = 0; if (DownloadList.thisInstance != null) { DownloadList.thisInstance.runOnUiThread( DownloadList.thisInstance.new DownloadProgressUpdater((int) (TotalSize / 1000), (int) (downloadedSize / 1000))); } mBuilder.setProgress((int) (TotalSize / 1000), (int) (downloadedSize / 1000), false) .setContentTitle(this.context.getResources().getString(R.string.downloading) + " " + StaticBlob.current_download + " " + this.context.getResources().getString(R.string.of) + " " + downloading_count + " - " + percentDone + "% (" + df.format(avg_speed) + "kb/s)") .setContentText(Show + ": " + Title); // Displays the progress bar for the first time. mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } } // END download of single file outStream.flush(); outStream.close(); inStream.close(); if (inner_failures == INNER_LIMIT) { throw new Exception("Inner exception has passed " + INNER_LIMIT); } Cursor active = StaticBlob.databaseConnector.getActiveDownloads(); if (StaticBlob.databaseConnector.getActiveDownloads().getCount() == 0) canceled = true; else { active.moveToFirst(); canceled = active.getLong(active.getColumnIndex("identity")) != identity; } if (!canceled) { Log.i(TAG, "Trying to finish with " + Target.length() + "==" + TotalSize); if (Target.length() == TotalSize) { StaticBlob.current_download++; Log.i(TAG, (inner_failures < INNER_LIMIT ? "Successfully" : "FAILED") + " downloaded to : " + Target.getPath()); //Move the download from active to completed. StaticBlob.databaseConnector.markDownloadComplete(id); Log.i(TAG, " " + DownloadList.rebuildHeaderThings); if (DownloadList.rebuildHeaderThings != null) DownloadList.rebuildHeaderThings.sendEmptyMessage(0); boolean queue = PreferenceManager.getDefaultSharedPreferences(context) .getBoolean("download_to_queue", false); if (queue) { StaticBlob.databaseConnector.appendToQueue(identity, false, isVideo); StaticBlob.playerInfo.update(context); } //Episode Desc if (EpisodeDesc.currentInstance != null) EpisodeDesc.currentInstance.determineButtons(); //ShowList if (ShowList.thisInstance != null && ShowList.thisInstance.currentDownloadItem != null) { ShowList.thisInstance.runOnUiThread(ShowList.thisInstance.new updateBoldOrItalic(id, ShowList.thisInstance.currentDownloadItem, AudFile, VidFile, AudSize, VidSize)); ShowList.thisInstance.currentDownloadItem = null; } } } else Target.delete(); } catch (ParseException e) { Log.e(TAG + ":ParseException", "Error parsing a date from the SQLite db: "); Log.e(TAG + ":ParseException", Date); Log.e(TAG + ":ParseException", "(This should never happen)."); outer_failures++; e.printStackTrace(); } catch (Exception e) { outer_failures++; Log.e(TAG + ":Exception " + e.getClass(), "[" + outer_failures + "] Msg: " + e.getMessage()); e.printStackTrace(); try { Thread.sleep(1000); } catch (InterruptedException e1) { } } if (outer_failures == OUTER_LIMIT) { boolean quit = false; //if(quit = aDownloads.charAt(1)=='x') // aDownloads = aDownloads.replaceAll("x",""); quit = true; if (DownloadList.rebuildHeaderThings != null) DownloadList.rebuildHeaderThings.sendEmptyMessage(0); failed++; outer_failures = 0; if (quit) break; } } Log.i(TAG, "Finished Downloading"); if (DownloadList.thisInstance != null) DownloadList.thisInstance.updateMenu(); //Wifi lock if (DownloadList.Download_wifiLock != null && DownloadList.Download_wifiLock.isHeld()) DownloadList.Download_wifiLock.release(); //Notification mNotificationManager.cancel(NOTIFICATION_ID); if (downloading_count > 0) { mBuilder.setProgress(100, 0, false) .setContentTitle("Finished downloading " + downloading_count + " files"); if (failed > 0) mBuilder.setContentText(failed + " failed, try them again later"); mBuilder.setAutoCancel(true); mBuilder.setOngoing(false); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); StaticBlob.current_download = 1; downloading_count = 0; } else { StaticBlob.current_download = 1; downloading_count = 0; return false; } return true; }
From source file:org.apache.olingo.fit.tecsvc.http.DerivedAndMixedTypeTestITCase.java
@Test public void queryESTwoPrimWithEntityTypeCastInFilter() throws Exception { URL url = new URL(SERVICE_URI + "ESTwoPrim?$filter=olingo.odata.test1.ETBase/" + "AdditionalPropertyString_5%20eq%20%27TEST%20A%200815%27"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=full"); connection.connect();/*ww w . jav a 2 s . c o m*/ assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.JSON_FULL_METADATA, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE))); final String content = IOUtils.toString(connection.getInputStream()); assertTrue(content.contains( "\"value\":[{\"@odata.type\":\"#olingo.odata.test1.ETBase\"," + "\"@odata.id\":\"ESBase(111)\"," + "\"PropertyInt16@odata.type\":\"#Int16\"," + "\"PropertyInt16\":111," + "\"PropertyString\":\"TEST A\"," + "\"AdditionalPropertyString_5\":\"TEST A 0815\"" + ",\"#olingo.odata.test1.BAETBaseETTwoBaseRTETTwoBase\":" + "{\"title\":\"olingo.odata.test1.BAETBaseETTwoBaseRTETTwoBase\"," + "\"target\":\"ESBase(111)/olingo.odata.test1.BAETBaseETTwoBaseRTETTwoBase\"}}]")); }
From source file:org.atricore.idbus.capabilities.josso.test.JOSSO11WebSSORouteTest.java
public void testJOSSO11AuthNRequestToSAMLR2() throws Exception { String location = null;/*w ww . j ava 2 s .c om*/ URL spUrl = new URL("http://localhost:8181/JOSSO11/BIND/CH1?cmd=login"); HttpURLConnection urlConn = (HttpURLConnection) spUrl.openConnection(); urlConn.setInstanceFollowRedirects(false); urlConn.connect(); String headerName = null; String jossoSession = null; for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) { if (headerName.equals("Location")) { location = urlConn.getHeaderField(i); } } assert location != null; }
From source file:org.atricore.idbus.capabilities.josso.test.JOSSO11WebSSORouteTest.java
public void testSAMLR2AuthnToJOSSO11() throws Exception { String location = null;/* www .java 2s .c o m*/ URL spUrl = new URL("http://localhost:8181/JOSSO11/BIND/CH2?SAMLRequest=" + BASE64_SAMLR2_AUTHNREQUEST); HttpURLConnection urlConn = (HttpURLConnection) spUrl.openConnection(); urlConn.setInstanceFollowRedirects(false); urlConn.connect(); String headerName = null; String jossoSession = null; for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) { if (headerName.equals("Location")) { location = urlConn.getHeaderField(i); } } assert location != null; }
From source file:org.callimachusproject.test.WebResource.java
public byte[] get(String type) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Accept", type); con.setRequestProperty("Accept-Encoding", "gzip"); Assert.assertEquals(con.getResponseMessage(), 200, con.getResponseCode()); InputStream in = con.getInputStream(); try {/*w ww. j a v a 2 s. c o m*/ if ("gzip".equals(con.getHeaderField("Content-Encoding"))) { in = new GZIPInputStream(in); } ByteArrayOutputStream out = new ByteArrayOutputStream(); ChannelUtil.transfer(in, out); return out.toByteArray(); } finally { in.close(); } }
From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.AbstractApiControllerTest.java
@NotNull protected Tuple2<Integer, String> fetchText(final String rel, final String expectedContentType) throws Exception { final HttpURLConnection conn = (HttpURLConnection) resolve(rel).toURL().openConnection(); try {//from w w w. j a v a2s. com conn.setRequestProperty("Accept", expectedContentType); conn.connect(); final int responseCode = conn.getResponseCode(); InputStream in; try { in = conn.getInputStream(); } catch (final IOException e) { in = conn.getErrorStream(); } if (in == null) { return Tuple2.tuple2(responseCode, ""); } assertEquals(expectedContentType, conn.getHeaderField("Content-Type")); try { final StringBuilder sb = new StringBuilder(); int rd; while ((rd = in.read()) != -1) { sb.append((char) rd); } return Tuple2.tuple2(responseCode, sb.toString()); } finally { in.close(); } } finally { conn.disconnect(); } }
From source file:org.apache.olingo.fit.tecsvc.http.DerivedAndMixedTypeTestITCase.java
@Test public void queryESCompCollDerivedJsonFull() throws Exception { URL url = new URL(SERVICE_URI + "ESCompCollDerived"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=full"); connection.setRequestMethod(HttpMethod.GET.name()); connection.connect();//from w ww .j a v a 2s . c om assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.JSON_FULL_METADATA, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE))); final String content = IOUtils.toString(connection.getInputStream()); assertTrue(content.contains("\"PropertyInt16\":32767,\"PropertyCompAno\":null," + "\"CollPropertyCompAno@odata.type\":\"#Collection(olingo.odata.test1.CTTwoPrimAno)\"," + "\"CollPropertyCompAno\":[{\"@odata.type\":" + "\"#olingo.odata.test1.CTTwoPrimAno\",\"PropertyString\":\"TEST9876\"}]}," + "{\"@odata.type\":\"#olingo.odata.test1.ETDeriveCollComp\",\"@odata.id\":\"ESCompCollDerived(12345)\"," + "\"PropertyInt16@odata.type\":\"#Int16\",\"PropertyInt16\":12345,\"PropertyCompAno\":" + "{\"@odata.type\":\"#olingo.odata.test1.CTBaseAno\"," + "\"PropertyString\":\"Num111\",\"AdditionalPropString\":\"Test123\"}," + "\"CollPropertyCompAno@odata.type\":\"#Collection(olingo.odata.test1.CTTwoPrimAno)\",\"CollPropertyCompAno\":" + "[{\"@odata.type\":\"#olingo.odata.test1.CTBaseAno\"," + "\"PropertyString\":\"TEST12345\",\"AdditionalPropString\":\"Additional12345\"}," + "{\"@odata.type\":\"#olingo.odata.test1.CTTwoPrimAno\",\"PropertyString\":\"TESTabcd\"}]}]}")); }
From source file:net.mceoin.cominghome.api.NestUtil.java
private static String getNestAwayStatusCall(String access_token) { String away_status = ""; String urlString = "https://developer-api.nest.com/structures?auth=" + access_token; log.info("url=" + urlString); StringBuilder builder = new StringBuilder(); boolean error = false; String errorResult = ""; HttpURLConnection urlConnection = null; try {/*from w w w. j av a 2 s .c o m*/ URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0"); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setConnectTimeout(15000); urlConnection.setReadTimeout(15000); // urlConnection.setChunkedStreamingMode(0); // urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); boolean redirect = false; // normally, 3xx is redirect int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 // Temporary redirect || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } // System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = urlConnection.getHeaderField("Location"); // open the new connnection again urlConnection = (HttpURLConnection) new URL(newUrl).openConnection(); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); // urlConnection.setChunkedStreamingMode(0); // System.out.println("Redirect to URL : " + newUrl); } int statusCode = urlConnection.getResponseCode(); log.info("statusCode=" + statusCode); if ((statusCode == HttpURLConnection.HTTP_OK)) { error = false; InputStream response; response = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); JSONObject structure = object.getJSONObject(key); if (structure.has("away")) { away_status = structure.getString("away"); } else { log.info("missing away"); } } } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { // bad auth error = true; errorResult = "Unauthorized"; } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { error = true; InputStream response; response = urlConnection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("error")) { // error = Internal Error on bad structure_id errorResult = object.getString("error"); log.info("errorResult=" + errorResult); } } } else { error = true; errorResult = Integer.toString(statusCode); } } catch (IOException e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("IOException: " + errorResult); } catch (Exception e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("Exception: " + errorResult); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (error) away_status = "Error: " + errorResult; return away_status; }