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:com.pushinginertia.commons.net.client.AbstractHttpPostClient.java
/** * Verifies that the response code is {@link java.net.HttpURLConnection#HTTP_OK}. * * @param con instantiated connection//from w w w. java 2s. c o m * @throws HttpConnectException if the response code is bad or some communication problem with the remote host occurs */ protected void verifyResponseCode(final HttpURLConnection con) throws HttpConnectException { try { if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { final String msg = "Bad HTTP response code [" + con.getResponseCode() + ": " + con.getResponseMessage() + "] reported by host: " + getHostName(); LOG.error(getClass().getSimpleName(), msg); throw new HttpConnectException(msg); } } catch (HttpConnectException e) { // don't double-wrap the exception! throw e; } catch (Exception e) { final String msg = "An unexpected error occurred while reading the response code from [" + getUrl() + "]: " + e.getMessage(); LOG.error(getClass().getSimpleName(), msg, e); throw new HttpConnectException(msg, e); } }
From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java
public String responseCaptcha(String responseCaptcha) { String url = "https://ipv4.google.com/sorry/CaptchaRedirect"; String request = url + "?q=" + q + "&hl=es&continue=" + continueCaptcha + "&id=" + idCaptcha + "&captcha=" + responseCaptcha + "&submit=Enviar"; String newCookie = ""; try {// w ww.jav a2 s . c o m URL obj = new URL(request); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); // add request header con.setRequestProperty("Host", "ipv4.google.com"); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0"); con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); con.setRequestProperty("Accept-Language", "es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3"); con.setRequestProperty("Accept-Encoding", "gzip, deflate, br"); con.setRequestProperty("Cookie", tokenCookie + "; path=/; domain=google.com"); con.addRequestProperty("Connection", "keep-alive"); con.setRequestProperty("Referer", referer); //con.connect(); boolean redirect = false; con.setInstanceFollowRedirects(false); int status = con.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { // get redirect url from "location" header field String newUrl = con.getHeaderField("Location"); // open the new connnection again con = (HttpURLConnection) new URL(newUrl).openConnection(); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0"); con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); con.setRequestProperty("Referer", referer); con.setRequestProperty("Accept-Encoding", "gzip, deflate"); con.setRequestProperty("Cookie", tokenCookie); con.addRequestProperty("Connection", "keep-alive"); // Find the cookie String nextURL = URLDecoder.decode(newUrl, "UTF-8"); String[] k = nextURL.split("&"); for (String a : k) { if (a.startsWith("google_abuse=")) { String temp = a.replace("google_abuse=", ""); String[] c = temp.split(";"); for (String j : c) { if (j.startsWith("GOOGLE_ABUSE_EXEMPTION")) { newCookie = j; } } } } } con.connect(); if (con.getResponseCode() == 200) { newCookie = tokenCookie; } } catch (IOException e) { e.printStackTrace(); } return newCookie; }
From source file:de.ub0r.android.websms.connector.gmx.ConnectorGMX.java
@Override protected void parseResponseCode(final Context context, final HttpResponse response) { final int resp = response.getStatusLine().getStatusCode(); switch (resp) { case HttpURLConnection.HTTP_OK: return;//from w w w . j a v a2s . c o m case HttpURLConnection.HTTP_ACCEPTED: return; case HttpURLConnection.HTTP_FORBIDDEN: throw new WebSMSException(context, R.string.error_pw); default: super.parseResponseCode(context, response); break; } }
From source file:com.commsen.jwebthumb.WebThumbService.java
private HttpURLConnection getFetchConnection(WebThumbFetchRequest webThumbFetchRequest) throws WebThumbException { Validate.notNull(webThumbFetchRequest, "webThumbFetchRequest is null!"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Attempting to send webThumbFetchRequest: " + webThumbFetchRequest); }//from w w w . ja v a 2 s . co m WebThumb webThumb = new WebThumb(apikey, webThumbFetchRequest); try { HttpURLConnection connection = (HttpURLConnection) new URL(WEB_THUMB_URL).openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setRequestMethod("POST"); SimpleXmlSerializer.generateRequest(webThumb, connection.getOutputStream()); int responseCode = connection.getResponseCode(); String contentType = getContentType(connection); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("webThumbFetchRequest sent. Got response: " + responseCode + " " + connection.getResponseMessage()); LOGGER.fine("Content type: " + contentType); } if (responseCode == HttpURLConnection.HTTP_OK) { if (CONTENT_TYPE_TEXT_PLAIN.equals(contentType)) { throw new WebThumbException( "Server side error: " + IOUtils.toString(connection.getInputStream())); } return connection; } else if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { WebThumbResponse webThumbResponse = SimpleXmlSerializer.parseResponse(connection.getErrorStream(), WebThumbResponse.class); throw new WebThumbException("Server side error: " + webThumbResponse.getError().getValue()); } else { throw new WebThumbException("Server side error: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (MalformedURLException e) { throw new WebThumbException("failed to send request", e); } catch (IOException e) { throw new WebThumbException("failed to send request", e); } }
From source file:de.ub0r.android.websms.connector.smsclub.ConnectorSmsClub.java
private String doHttpRequest(final Context context, final HttpOptions options) throws IOException { // send message HttpResponse response = Utils.getHttpClient(options); // evaluate response int resp = response.getStatusLine().getStatusCode(); if (resp != HttpURLConnection.HTTP_OK) { this.checkReturnCode(context, resp); throw new WebSMSException(context, R.string.error_http, " " + resp); }/*from w w w . j a v a 2 s . c o m*/ String htmlText = Utils.stream2str(response.getEntity().getContent()).trim(); return htmlText; }
From source file:com.cloudera.hoop.client.fs.HoopFileSystem.java
/** * Opens an FSDataInputStream at the indicated Path. * </p>// w w w .j a va 2s . c o m * IMPORTANT: the returned <code><FSDataInputStream/code> does not support the * <code>PositionReadable</code> and <code>Seekable</code> methods. * * @param f the file name to open * @param bufferSize the size of the buffer to be used. */ @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { Map<String, String> params = new HashMap<String, String>(); HttpURLConnection conn = getConnection("GET", params, f); validateResponse(conn, HttpURLConnection.HTTP_OK); return new FSDataInputStream(new HoopFSDataInputStream(conn.getInputStream(), bufferSize)); }
From source file:com.niroshpg.android.gmail.CronHandlerServlet.java
public BigInteger getHistoryIdXX(Gmail service, String userId, Credential credential) throws IOException { BigInteger historyId = null;//from w w w.j a va 2s . co m try { URL url = new URL("https://www.googleapis.com/gmail/v1/users/" + userId + "/profile"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //credential.refreshToken(); connection.setRequestProperty("Authorization", "Bearer " + credential.getAccessToken()); connection.setRequestProperty("Content-Type", "application/json"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // OK BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer res = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { res.append(line); logger.warning(line); } reader.close(); JSONObject jsonObj = new JSONObject(res); historyId = BigInteger.valueOf(jsonObj.getLong("historyId")); } else { // Server returned HTTP error code. logger.warning("failed : " + connection.getResponseCode()); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String error = ""; String text; while ((text = br.readLine()) != null) { error += text; } logger.warning("error : " + error); } } catch (Exception e) { logger.warning("exception : " + e.getMessage() + " , " + e.getStackTrace().toString()); } return historyId; }
From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getBitcoinCharts() { try {//from w w w. j ava2 s . c o m Double btcRate = 0.0; Object result = getCoinValueBTC(); if (result == null) return null; else btcRate = (Double) result; final URL URL = new URL("http://api.bitcoincharts.com/v1/weighted_prices.json"); final HttpURLConnection connection = (HttpURLConnection) URL.openConnection(); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.connect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) return null; Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); //Add Bitcoin information rates.put(CoinDefinition.cryptsyMarketCurrency, new ExchangeRate(CoinDefinition.cryptsyMarketCurrency, Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")), "pubapi.cryptsy.com")); final JSONObject head = new JSONObject(content.toString()); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); if (!"timestamp".equals(currencyCode)) { final JSONObject o = head.getJSONObject(currencyCode); String rate = o.optString("24h", null); if (rate == null) rate = o.optString("7d", null); if (rate == null) rate = o.optString("30d", null); double rateForBTC = Double.parseDouble(rate); rate = String.format("%.8f", rateForBTC * btcRate); if (rate != null) { try { rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost())); } catch (final ArithmeticException x) { log.debug("problem reading exchange rate: " + currencyCode, x); } } } } return rates; } finally { if (reader != null) reader.close(); } } catch (final Exception x) { log.debug("problem reading exchange rates", x); } return null; }
From source file:com.hortonworks.registries.auth.client.AuthenticatorTestCase.java
private void doHttpClientRequest(HttpClient httpClient, HttpUriRequest request) throws Exception { HttpResponse response = null;//w ww .j ava2 s . c o m try { response = httpClient.execute(request); final int httpStatus = response.getStatusLine().getStatusCode(); Assert.assertEquals(HttpURLConnection.HTTP_OK, httpStatus); } finally { if (response != null) EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:mobac.mapsources.loader.MapPackManager.java
public String downloadMD5SumList() throws IOException, UpdateFailedException { String md5eTag = Settings.getInstance().mapSourcesUpdate.etag; log.debug("Last md5 eTag: " + md5eTag); String updateUrl = System.getProperty("mobac.updateurl"); if (updateUrl == null) throw new RuntimeException("Update url not present"); byte[] data = null; // Proxy p = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved("localhost", 8888)); HttpURLConnection conn = (HttpURLConnection) new URL(updateUrl).openConnection(); conn.setInstanceFollowRedirects(false); if (md5eTag != null) conn.addRequestProperty("If-None-Match", md5eTag); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) { log.debug("No newer md5 file available"); return null; }//from w ww . j a v a 2 s .co m if (responseCode != HttpURLConnection.HTTP_OK) throw new UpdateFailedException( "Invalid HTTP response: " + responseCode + " for update url " + conn.getURL()); // Case HTTP_OK InputStream in = conn.getInputStream(); data = Utilities.getInputBytes(in); in.close(); Settings.getInstance().mapSourcesUpdate.etag = conn.getHeaderField("ETag"); log.debug("New md5 file retrieved"); String md5sumList = new String(data); return md5sumList; }