List of usage examples for java.net HttpURLConnection HTTP_OK
int HTTP_OK
To view the source code for java.net HttpURLConnection HTTP_OK.
Click Source Link
From source file:org.gameontext.regsvc.RatingEndpoint.java
/** * GET /regsvc/v1/rate/*www . j a va2s. com*/ * @throws JsonProcessingException */ @GET @ApiOperation(value = "List rooms ratings", notes = "Provides a list of room ratings for a given event.", code = HttpURLConnection.HTTP_OK) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getRatings() { return Response.ok(repo.getRatings()).build(); }
From source file:com.delaroystudios.weatherapp.utilities.OpenWeatherJsonUtils.java
/** * This method parses JSON from a web response and returns an array of Strings * describing the weather over various days from the forecast. * <p/>/*from w w w .j ava 2s . c o m*/ * Later on, we'll be parsing the JSON into structured data within the * getFullWeatherDataFromJson function, leveraging the data we have stored in the JSON. For * now, we just convert the JSON into human-readable strings. * * @param forecastJsonStr JSON response from server * * @return Array of Strings describing weather data * * @throws JSONException If JSON data cannot be properly parsed */ public static String[] getSimpleWeatherStringsFromJson(Context context, String forecastJsonStr) throws JSONException { /* Weather information. Each day's forecast info is an element of the "list" array */ final String OWM_LIST = "list"; /* All temperatures are children of the "temp" object */ final String OWM_TEMPERATURE = "temp"; /* Max temperature for the day */ final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_MESSAGE_CODE = "cod"; /* String array to hold each day's weather String */ String[] parsedWeatherData = null; JSONObject forecastJson = new JSONObject(forecastJsonStr); /* Is there an error? */ if (forecastJson.has(OWM_MESSAGE_CODE)) { int errorCode = forecastJson.getInt(OWM_MESSAGE_CODE); switch (errorCode) { case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_NOT_FOUND: /* Location invalid */ return null; default: /* Server probably down */ return null; } } JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); parsedWeatherData = new String[weatherArray.length()]; long localDate = System.currentTimeMillis(); long utcDate = WeatherDateUtils.getUTCDateFromLocal(localDate); long startDay = WeatherDateUtils.normalizeDate(utcDate); for (int i = 0; i < weatherArray.length(); i++) { String date; String highAndLow; /* These are the values that will be collected */ long dateTimeMillis; double high; double low; String description; /* Get the JSON object representing the day */ JSONObject dayForecast = weatherArray.getJSONObject(i); /* * We ignore all the datetime values embedded in the JSON and assume that * the values are returned in-order by day (which is not guaranteed to be correct). */ dateTimeMillis = startDay + WeatherDateUtils.DAY_IN_MILLIS * i; date = WeatherDateUtils.getFriendlyDateString(context, dateTimeMillis, false); /* * Description is in a child array called "weather", which is 1 element long. * That element also contains a weather code. */ JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); /* * Temperatures are sent by Open Weather Map in a child object called "temp". * * Editor's Note: Try not to name variables "temp" when working with temperature. * It confuses everybody. Temp could easily mean any number of things, including * temperature, temporary and is just a bad variable name. */ JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); highAndLow = WeatherUtils.formatHighLows(context, high, low); parsedWeatherData[i] = date + " - " + description + " - " + highAndLow; } return parsedWeatherData; }
From source file:com.couchbase.client.TestOperationImpl.java
@Override public void handleResponse(HttpResponse response) { String json = getEntityString(response); int errorcode = response.getStatusLine().getStatusCode(); if (errorcode == HttpURLConnection.HTTP_OK) { ((TestCallback) callback).getData(json); callback.receivedStatus(new OperationStatus(true, "OK")); } else {/*from ww w .j av a 2 s .com*/ callback.receivedStatus(new OperationStatus(false, Integer.toString(errorcode))); } callback.complete(); }
From source file:com.QuarkLabs.BTCeClient.exchangeApi.SimpleRequest.java
/** * Makes simple non-authenticated request * * @param urlString URL of Trade API/*w ww. j a v a2s.c o m*/ * @return Response of type JSONObject * @throws JSONException */ @Nullable public JSONObject makeRequest(String urlString) throws JSONException { HttpURLConnection connection = null; BufferedReader rd = null; try { URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); InputStream response = connection.getInputStream(); StringBuilder sb = new StringBuilder(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { rd = new BufferedReader(new InputStreamReader(response)); String line; while ((line = rd.readLine()) != null) { sb.append(line); } return new JSONObject(sb.toString()); } } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (rd != null) { try { rd.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }
From source file:org.gameontext.regsvc.RegistrationEndpoint.java
/** * GET /regsvc/v1/register//from www. ja v a2 s. c o m * @throws JsonProcessingException */ @GET @ApiOperation(value = "List rooms registered for events", notes = "Provides a list of rooms that are registered for a given event.", code = HttpURLConnection.HTTP_OK) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getRegistrations() { return Response.ok(repo.getRegistrations()).build(); }
From source file:com.michelin.cio.hudson.plugins.qc.QualityCenterUtils.java
/** * Checks the Quality Center server URL. *//* www .jav a 2 s . co m*/ public static FormValidation checkQcServerURL(String value, Boolean acceptEmpty) { String url; // Path to the page to check if the server is alive String page = "servlet/tdservlet/TDAPI_GeneralWebTreatment"; // Do will allow empty value? if (StringUtils.isBlank(value)) { if (!acceptEmpty) { return FormValidation.error(Messages.QualityCenter_ServerURLMustBeDefined()); } else { return FormValidation.ok(); } } // Does the URL ends with a "/" ? if not, add it if (value.lastIndexOf("/") == value.length() - 1) { url = value + page; } else { url = value + "/" + page; } // Open the connection and perform a HEAD request HttpURLConnection connection; try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("HEAD"); // Check the response code if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return FormValidation.error(connection.getResponseMessage()); } } catch (MalformedURLException ex) { // This is not a valid URL return FormValidation.error(Messages.QualityCenter_MalformedServerURL()); } catch (IOException ex) { // Cant open connection to the server return FormValidation.error(Messages.QualityCenter_ErrorOpeningServerConnection()); } return FormValidation.ok(); }
From source file:com.fastbootmobile.encore.api.common.HttpGet.java
/** * Downloads the data from the provided URL. * @param inUrl The URL to get from/*from www . ja v a2 s . co m*/ * @param query The query field. '?' + query will be appended automatically, and the query data * MUST be encoded properly. * @return A byte array of the data */ public static byte[] getBytes(String inUrl, String query, boolean cached) throws IOException, RateLimitException { final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query)); Log.d(TAG, "Formatted URL: " + formattedUrl); URL url = new URL(formattedUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)"); urlConnection.setUseCaches(cached); urlConnection.setInstanceFollowRedirects(true); int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale); try { final int status = urlConnection.getResponseCode(); // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway. if (status == HttpURLConnection.HTTP_OK) { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); int contentLength = urlConnection.getContentLength(); if (contentLength <= 0) { // No length? Let's allocate 100KB. contentLength = 100 * 1024; } ByteArrayBuffer bab = new ByteArrayBuffer(contentLength); BufferedInputStream bis = new BufferedInputStream(in); int character; while ((character = bis.read()) != -1) { bab.append(character); } return bab.toByteArray(); } else if (status == HttpURLConnection.HTTP_NOT_FOUND) { // 404 return new byte[] {}; } else if (status == HttpURLConnection.HTTP_FORBIDDEN) { return new byte[] {}; } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) { throw new RateLimitException(); } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */ || status == HttpURLConnection.HTTP_SEE_OTHER) { // We've been redirected, follow the new URL final String followUrl = urlConnection.getHeaderField("Location"); Log.e(TAG, "Redirected to: " + followUrl); return getBytes(followUrl, "", cached); } else { Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")"); return new byte[] {}; } } finally { urlConnection.disconnect(); } }
From source file:com.pkrete.locationservice.admin.util.WebUtil.java
/** * Checks if the given URL exists.//from w ww.j a va 2 s . co m * * @param url the URL to be checked * @return if the URL is exists returns true, otherwise returns false */ public static boolean exists(String url) { try { HttpURLConnection.setFollowRedirects(true); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); // HTTP statuses 200 and 302 are accepted return (con.getResponseCode() == HttpURLConnection.HTTP_OK || con.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP); } catch (Exception e) { logger.error(e.getMessage(), e); return false; } }
From source file:net.sf.ehcache.constructs.web.filter.GzipFilterTest.java
/** * Fetch NoFiltersPage.jsp, which is excluded from all filters and check it is not gzipped. *///from w w w .j a v a 2 s.c o m public void testNegativeGzip() throws Exception { WebConversation client = createWebConversation(true); client.getClientProperties().setAcceptGzip(true); String url = buildUrl("/NoFiltersPage.jsp"); WebResponse response = client.getResponse(url); assertNotNull(response); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); String responseURL = response.getURL().toString(); assertEquals(url, responseURL); assertNotSame("gzip", response.getHeaderField("Content-Encoding")); }
From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java
/** * Check if specified dataset already exists on server * //from www . j a v a 2 s . c o m * @param dataSetName * @return boolean true if the dataset already exits, false if not * @throws IOException * @throws HttpException */ public static boolean chechIfExist(String dataSetName) throws IOException, HttpException { boolean exists = false; URL url = new URL(HOST + "/$/datasets/" + dataSetName); final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setUseCaches(false); httpConnection.setRequestMethod("GET"); // handle HTTP/HTTPS strange behaviour httpConnection.connect(); httpConnection.disconnect(); // handle response switch (httpConnection.getResponseCode()) { case HttpURLConnection.HTTP_OK: exists = true; break; case HttpURLConnection.HTTP_NOT_FOUND: break; default: throw new HttpException( httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage()); } return exists; }