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:br.eti.ranieri.opcoesweb.importacao.offline.ImportadorOffline.java
public void importar(URL url, ConfiguracaoImportacao configuracaoImportacao) throws Exception { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new Exception("Requisio HTTP retornou cdigo de erro: " + connection.getResponseCode()); }//from ww w. ja v a 2 s . c o m List<CotacaoBDI> cotacoes = null; ZipInputStream zip = null; try { zip = new ZipInputStream(connection.getInputStream()); ZipEntry entry; while ((entry = zip.getNextEntry()) != null) { if ("BDIN".equals(entry.getName())) { cotacoes = parser.parseBDI(zip); zip.closeEntry(); break; } else if (entry.getName().startsWith("COTAHIST_") && entry.getName().endsWith(".TXT")) { cotacoes = parser.parseHistorico(zip); zip.closeEntry(); break; } } zip.close(); } catch (ZipException e) { log.error("Formato invalido de arquivo zip", e); } catch (IOException e) { log.error("Erro de leitura do arquivo zip", e); } finally { if (zip != null) IOUtils.closeQuietly(zip); } calcularBlackScholes(cotacoes, configuracaoImportacao); }
From source file:com.urhola.vehicletracker.connection.mattersoft.MatterSoftLiveHelsinki.java
private HttpURLConnection getOpenedConnection(List<NameValuePair> params, String responseMethod) throws ConnectionException { HttpURLConnection urlConnection; try {//w w w . ja v a 2 s. co m URIBuilder b = new URIBuilder(BASE_URL); b.addParameters(params); URL url = b.build().toURL(); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestMethod(responseMethod); urlConnection.setReadTimeout(TIME_OUT_LENGTH); urlConnection.setConnectTimeout(TIME_OUT_LENGTH); urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) throw new ConnectionException(urlConnection.getResponseMessage()); return urlConnection; } catch (URISyntaxException | IOException ex) { throw new ConnectionException(ex); } }
From source file:io.pivotal.demo.smartgrid.frontend.timeseries.AggregateCounterTimeSeriesRepository.java
private void pingXdServer() { try {//from ww w. j av a 2 s. c om HttpURLConnection con = (HttpURLConnection) new URL(xdServerBaseUrl).openConnection(); con.setRequestMethod("HEAD"); int timeout = 2000; con.setReadTimeout(timeout); con.setConnectTimeout(timeout); int responseCode = con.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { LOG.error("Bad response from server: {} Response: {}", xdServerBaseUrl, responseCode); } } catch (Exception ex) { LOG.error("Could not connect to server: {} Error: {}: {}", xdServerBaseUrl, ex.getClass().getSimpleName(), ex.getMessage()); } }
From source file:com.couchbase.client.protocol.views.ViewFetcherOperationImpl.java
@Override public void handleResponse(HttpResponse response) { String json = getEntityString(response); try {/*from w ww .j av a 2 s . co m*/ View view = parseDesignDocumentForView(bucketName, designDocName, viewName, json); int errorcode = response.getStatusLine().getStatusCode(); if (errorcode == HttpURLConnection.HTTP_OK) { ((ViewFetcherCallback) callback).gotData(view); callback.receivedStatus(new OperationStatus(true, "OK")); } else { callback.receivedStatus(new OperationStatus(false, Integer.toString(errorcode))); } } catch (ParseException e) { exception = new OperationException(OperationErrorType.GENERAL, "Error parsing JSON"); } callback.complete(); }
From source file:org.cytoscape.app.internal.net.server.ScreenOriginsBeforeResponseTest.java
@Test public void testScreenOrigins() throws Exception { final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2609)); final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl(); httpd.addResponder(new CyHttpResponder() { public Pattern getURIPattern() { return Pattern.compile("^/test$"); }//from ww w . j a va 2 s. c om public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) { return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html"); } }); httpd.addBeforeResponse(new ScreenOriginsBeforeResponse("http://x", "http://y")); httpd.start(); HttpURLConnection connection = null; final String url = "http://localhost:2609/test"; connection = connectToURL(url, "GET", null); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN); connection = connectToURL(url, "GET", "http://x"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); connection = connectToURL(url, "GET", "http://y"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); connection = connectToURL(url, "GET", "http://z"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN); httpd.stop(); }
From source file:com.couchbase.client.protocol.views.SpatialViewFetcherOperationImpl.java
@Override public void handleResponse(HttpResponse response) { String json = getEntityString(response); try {/*from www.j a va2 s . c o m*/ SpatialView view = parseDesignDocumentForView(bucketName, designDocName, viewName, json); int errorcode = response.getStatusLine().getStatusCode(); if (errorcode == HttpURLConnection.HTTP_OK) { ((SpatialViewFetcherOperation.ViewFetcherCallback) callback).gotData(view); callback.receivedStatus(new OperationStatus(true, "OK")); } else { callback.receivedStatus(new OperationStatus(false, Integer.toString(errorcode))); } } catch (ParseException e) { exception = new OperationException(OperationErrorType.GENERAL, "Error parsing JSON"); } callback.complete(); }
From source file:org.fao.geonet.utils.GeonetHttpRequestFactoryTest.java
@Test public void testReadUrl() throws Exception { final int port = 29483; InetSocketAddress address = new InetSocketAddress(port); HttpServer httpServer = HttpServer.create(address, 0); final Element expectedResponse = new Element("resource").addContent(new Element("id").setText("test")); HttpHandler requestHandler = new HttpHandler() { @Override/* www . j a v a 2 s. c o m*/ public void handle(HttpExchange exchange) throws IOException { byte[] response = Xml.getString(expectedResponse).getBytes(); exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length); exchange.getResponseBody().write(response); exchange.close(); } }; final String urlPath = "/1234.xml"; httpServer.createContext(urlPath, requestHandler); try { httpServer.start(); final XmlRequest xmlRequest = new GeonetHttpRequestFactory() .createXmlRequest(new URL("http://localhost:" + port + urlPath)); final Element response = xmlRequest.execute(); assertEquals(Xml.getString(expectedResponse), Xml.getString(response)); } finally { httpServer.stop(0); } }
From source file:i5.las2peer.services.two.Two.java
/** * /*w ww. j ava 2s. c o m*/ * test * * * * @return HttpResponse * */ @GET @Path("/test") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "testJson") }) @ApiOperation(value = "test", notes = " ") public HttpResponse test() { // testJson boolean testJson_condition = true; if (testJson_condition) { JSONObject testResult = new JSONObject(); HttpResponse testJson = new HttpResponse(testResult.toJSONString(), HttpURLConnection.HTTP_OK); return testJson; } return null; }
From source file:com.example.appengine.appidentity.UrlShortener.java
/** * Returns a shortened URL by calling the Google URL Shortener API. * * <p>Note: Error handling elided for simplicity. *///ww w . java 2 s. c om public String createShortUrl(String longUrl) throws Exception { ArrayList<String> scopes = new ArrayList<String>(); scopes.add("https://www.googleapis.com/auth/urlshortener"); final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes); // The token asserts the identity reported by appIdentity.getServiceAccountName() JSONObject request = new JSONObject(); request.put("longUrl", longUrl); URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken()); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); request.write(writer); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // Note: Should check the content-encoding. // Any JSON parser can be used; this one is used for illustrative purposes. JSONTokener responseTokens = new JSONTokener(connection.getInputStream()); JSONObject response = new JSONObject(responseTokens); return (String) response.get("id"); } else { try (InputStream s = connection.getErrorStream(); InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) { throw new RuntimeException(String.format("got error (%d) response %s from %s", connection.getResponseCode(), CharStreams.toString(r), connection.toString())); } } }
From source file:de.ingrid.mdek.quartz.jobs.util.URLValidator.java
public URLState call() { log.debug("checking url: " + urlState.getUrl()); String url = urlState.getUrl() + urlState.getAdditionalParams(); GetMethod getMethod = null;// w w w . j av a 2 s .c om long startTime = System.currentTimeMillis(); try { getMethod = new GetMethod(url); int responseCode = httpClient.executeMethod(getMethod); urlState.setResponseCode(responseCode); if (HttpURLConnection.HTTP_OK == responseCode) { urlState.setState(State.VALID); // get content for further analysis if page is ok // -> getResponseBodyAsString-method can easily lead to OOM!!! // responseString = getMethod.getResponseBodyAsString(); Reader reader = new InputStreamReader(getMethod.getResponseBodyAsStream(), getMethod.getResponseCharSet()); // consume the response entity responseString = getStringFromInputStream(reader, 10); } else { urlState.setState(State.HTTP_ERROR); } } catch (HTTPException ex) { urlState.setState(State.HTTP_ERROR); } catch (ConnectException ex) { urlState.setState(State.CONNECT_REFUSED); } catch (ConnectTimeoutException ex) { urlState.setState(State.CONNECT_TIMEOUT); } catch (SocketTimeoutException ex) { urlState.setState(State.SOCKET_TIMEOUT); } catch (UnknownHostException ex) { urlState.setState(State.UNKNOWN_HOST); } catch (IOException ex) { urlState.setState(State.HTTP_ERROR); } catch (IllegalArgumentException ex) { urlState.setState(State.MALFORMED_URL); } catch (Exception ex) { urlState.setState(State.HTTP_ERROR); } finally { if (getMethod != null) { getMethod.releaseConnection(); } } long endTime = System.currentTimeMillis(); log.debug("done after " + (endTime - startTime) + "ms: " + urlState.getUrl()); log.debug("returning: " + urlState.getState() + "(" + urlState.getResponseCode() + ")"); return urlState; }