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:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Checks if is reachable./*from ww w. j av a 2 s .c o m*/ * * @param uri the uri * @param headers the headers * @return true, if is reachable */ public static boolean isReachable(String uri, HashMap<String, String> headers) { try { HttpURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection myURLConnection = (HttpURLConnection) new URL(uri).openConnection(); myURLConnection.setRequestMethod("HEAD"); for (String key : headers.keySet()) { myURLConnection.setRequestProperty("Authorization", headers.get(key)); } LOGGER.info(myURLConnection.getResponseCode() + " / " + myURLConnection.toString()); return (myURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:com.shuffle.bitcoin.blockchain.Btcd.java
@Override protected boolean send(Bitcoin.Transaction t) throws ExecutionException, InterruptedException, CoinNetworkException { if (!t.canSend || t.sent) { return false; }// w ww . j av a 2s . c o m String hexTx = null; try { hexTx = DatatypeConverter.printHexBinary(t.bitcoinj().bitcoinSerialize()); } catch (BlockStoreException e) { return false; } catch (IOException er) { return false; } String requestBody = "{\"jsonrpc\":\"2.0\",\"id\":\"null\",\"method\":\"sendrawtransaction\", \"params\":[\"" + hexTx + "\"]}"; HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { return false; } connection.setDoOutput(true); try { connection.setRequestMethod("POST"); } catch (java.net.ProtocolException e) { return false; } connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); Base64 b = new Base64(); String authString = rpcuser + ":" + rpcpass; String encoding = b.encodeAsString(authString.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoding); connection.setRequestProperty("Content-Length", Integer.toString(requestBody.getBytes().length)); connection.setDoInput(true); OutputStream out; try { out = connection.getOutputStream(); } catch (IOException e) { return false; } try { out.write(requestBody.getBytes()); } catch (IOException e) { return false; } try { if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) return false; } catch (IOException e) { return false; } InputStream is; try { is = connection.getInputStream(); } catch (IOException e) { return false; } BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while (true) { try { if ((line = rd.readLine()) == null) break; } catch (IOException e) { return false; } response.append(line); response.append('\r'); } try { rd.close(); } catch (IOException e) { return false; } JSONObject json = new JSONObject(response.toString()); if (json.isNull("result")) { JSONObject errorObj = json.getJSONObject("error"); String errorMsg = errorObj.getString("message"); String parsed = errorMsg.substring(0, 37); // transaction is already in mempool, return true if (parsed.equals("TX rejected: already have transaction")) { return true; } throw new CoinNetworkException(errorMsg); } return true; }
From source file:net.sf.okapi.filters.drupal.DrupalConnector.java
/** * Logout and end session/*from ww w .ja v a2 s . c om*/ * @return */ boolean logout() { try { URL url = new URL(host + "rest/user/logout"); HttpURLConnection conn = createConnection(url, "POST", false); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { conn.disconnect(); return false; } conn.disconnect(); } catch (Throwable e) { throw new OkapiIOException("Error in logout().", e); } return true; }
From source file:co.forsaken.api.json.JsonWebCall.java
private boolean canConnect() throws Exception { try {/*from w w w . j av a 2s .c o m*/ HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(_url).openConnection(); con.setRequestMethod("HEAD"); con.setConnectTimeout(2000); if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new Exception("Service " + _url + " unavailable, oh no!"); } return true; } catch (java.net.SocketTimeoutException e) { throw new Exception("Service " + _url + " unavailable, oh no!", e); } catch (java.io.IOException e) { throw new Exception("Service " + _url + " unavailable, oh no!", e); } }
From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java
/** * Checks that the requested content type is returned when accept header explicitly set. *//* w w w . j a v a2 s .co m*/ @Test public void testContentTypeForGraphQuery1_GET() throws Exception { String query = "DESCRIBE <foo:bar>"; String location = TestServer.REPOSITORY_URL; location += "?query=" + URLEncoder.encode(query, "UTF-8"); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Request RDF/XML formatted results: conn.setRequestProperty("Accept", RDFFormat.RDFXML.getDefaultMIMEType()); conn.connect(); try { int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { String contentType = conn.getHeaderField("Content-Type"); assertNotNull(contentType); // snip off optional charset declaration int charPos = contentType.indexOf(";"); if (charPos > -1) { contentType = contentType.substring(0, charPos); } assertEquals(RDFFormat.RDFXML.getDefaultMIMEType(), contentType); } else { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); throw new RuntimeException(response); } } finally { conn.disconnect(); } }
From source file:net.praqma.jenkins.rqm.request.RQMHttpClient.java
public void followRedirects(HttpMethodBase method, int responseCode) throws HttpException, IOException { Header location = method.getResponseHeader("Location"); while (location != null && responseCode == HttpURLConnection.HTTP_MOVED_TEMP) { GetMethod get3 = new GetMethod(location.getValue()); responseCode = executeMethod(get3); if (responseCode != HttpURLConnection.HTTP_OK) { log.fine(String.format("Follow redirects returned code %s", responseCode)); }/*from w ww.j a v a 2 s.com*/ location = get3.getResponseHeader("Location"); } }
From source file:eu.gsmservice.android.websms.connector.gsmservice.ConnectorGsmService.java
/** * Send data.//from w w w . j a v a 2s . c o m * * @param fullTargetURL * @param context * @throws WebSMSException */ private void sendData(final String fullTargetURL, final Context context) throws WebSMSException { this.log("Start sendData"); try { this.log("sending url: " + fullTargetURL.toString()); HttpOptions httpOptions = new HttpOptions(ENCODING); httpOptions.url = fullTargetURL; httpOptions.userAgent = USER_AGENT; httpOptions.trustAll = true; this.log("send data: getHttpClient(...)"); HttpResponse response = Utils.getHttpClient(httpOptions); int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { throw new WebSMSException(context, R.string.error_http, "" + resp); } String htmlText = Utils.stream2str(response.getEntity().getContent()).trim(); if (htmlText == null || htmlText.length() == 0) { throw new WebSMSException(context, R.string.error_service); } htmlText = null; } catch (Exception e) { Log.e(TAG, "Error: " + e.getMessage(), e); throw new WebSMSException(e.getMessage()); } this.log("End sendData"); }
From source file:de.innovationgate.igutils.pingback.PingBackClient.java
/** * checks if the given sourceURI is reachable, has textual content and contains a link to the given target * if present the title of the sourceURI is returned * @param sourceURI - the sourceURI to check * @param targetURI - the targetURI to search as link * @throws PingBackException - thrown if check fails * @returns title of the sourceURI - null if not present or found *//*from w w w . j a v a2s.c o m*/ public String checkSourceURI(String sourceURI, String targetURI) throws PingBackException { HttpClient client = WGFactory.getHttpClientFactory().createHttpClient(); GetMethod sourceGET = new GetMethod(sourceURI); sourceGET.setFollowRedirects(false); try { int responseCode = client.executeMethod(sourceGET); if (responseCode != HttpURLConnection.HTTP_OK) { if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { throw new PingBackException(PingBackException.ERROR_ACCESS_DENIED, "Access denied on source uri '" + sourceURI + "'."); } else if (responseCode == HttpURLConnection.HTTP_BAD_GATEWAY) { throw new PingBackException(PingBackException.ERROR_UPSTREAM_SERVER_COMMUNICATION_ERROR, "Get request on source uri '" + sourceURI + "' returned '" + responseCode + "'."); } else { throw new PingBackException(PingBackException.ERROR_GENERIC, "Source uri is unreachable. Get request on source uri '" + sourceURI + "' returned '" + responseCode + "'."); } } checkTextualContentType(sourceGET); // search link to target in source InputStream sourceIn = sourceGET.getResponseBodyAsStream(); String searchTerm = targetURI.toLowerCase(); boolean linkFound = false; String title = null; if (sourceIn == null) { throw new PingBackException(PingBackException.ERROR_SOURCE_URI_HAS_NO_LINK, "Source uri contains no link to target '" + targetURI + "'."); } else { // first of all read response into a fix buffer of 2Mb - all further content will be ignored for doS-reason ByteArrayOutputStream htmlPageBuffer = new ByteArrayOutputStream(); inToOut(sourceGET.getResponseBodyAsStream(), htmlPageBuffer, 1024, documentSizeLimit); try { // search for title DOMParser parser = new DOMParser(); parser.parse(new InputSource(new ByteArrayInputStream(htmlPageBuffer.toByteArray()))); Document doc = parser.getDocument(); NodeList titleElements = doc.getElementsByTagName("title"); if (titleElements.getLength() > 0) { // retrieve first title Node titleNode = titleElements.item(0); title = titleNode.getFirstChild().getNodeValue(); } } catch (Exception e) { // ignore any parsing exception - title is just a goodie } // read line per line and search for link BufferedReader reader = new BufferedReader(new InputStreamReader( new ByteArrayInputStream(htmlPageBuffer.toByteArray()), sourceGET.getResponseCharSet())); String line = reader.readLine(); while (line != null) { line = line.toLowerCase(); if (line.indexOf(searchTerm) != -1) { linkFound = true; break; } line = reader.readLine(); } } if (!linkFound) { throw new PingBackException(PingBackException.ERROR_SOURCE_URI_HAS_NO_LINK, "Source uri '" + sourceURI + "' contains no link to target '" + targetURI + "'."); } else { return title; } } catch (HttpException e) { throw new PingBackException(PingBackException.ERROR_GENERIC, "Unable to check source uri '" + sourceURI + "'.", e); } catch (IOException e) { throw new PingBackException(PingBackException.ERROR_GENERIC, "Unable to check source uri '" + sourceURI + "'.", e); } }
From source file:fr.gael.dhus.service.ProductService.java
private static void wcsDeleteCoverage(String coverageId) throws IOException { String GET_URL = "http://localhost:8080/rasdaman/ows?SERVICE=WCS&VERSION=2.0.1&request=DeleteCoverage&coverageId=" + coverageId;//from ww w . j a v a 2s. c o m String USER_AGENT = "Mozilla/5.0"; URL obj = new URL(GET_URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) logger.info("Successfully deleted coverage with id " + coverageId); else logger.error("NoSuchCoverage"); }
From source file:org.apache.hadoop.hbase.http.TestSpnegoHttpServer.java
@Test public void testAllowedClient() throws Exception { // Create the subject for the client final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab); final Set<Principal> clientPrincipals = clientSubject.getPrincipals(); // Make sure the subject has a principal assertFalse(clientPrincipals.isEmpty()); // Get a TGT for the subject (might have many, different encryption types). The first should // be the default encryption type. Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class); assertFalse(privateCredentials.isEmpty()); KerberosTicket tgt = privateCredentials.iterator().next(); assertNotNull(tgt);//from w w w. j a v a 2s . c o m // The name of the principal final String principalName = clientPrincipals.iterator().next().getName(); // Run this code, logged in as the subject (the client) HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() { @Override public HttpResponse run() throws Exception { // Logs in with Kerberos via GSS GSSManager gssManager = GSSManager.getInstance(); // jGSS Kerberos login constant Oid oid = new Oid("1.2.840.113554.1.2.2"); GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME); GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY); HttpClientContext context = HttpClientContext.create(); Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build(); HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).build(); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential)); URL url = new URL(getServerURL(server), "/echo?a=b"); context.setTargetHost(new HttpHost(url.getHost(), url.getPort())); context.setCredentialsProvider(credentialsProvider); context.setAuthSchemeRegistry(authRegistry); HttpGet get = new HttpGet(url.toURI()); return client.execute(get, context); } }); assertNotNull(resp); assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode()); assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim()); }