Example usage for java.net HttpURLConnection getURL

List of usage examples for java.net HttpURLConnection getURL

Introduction

In this page you can find the example usage for java.net HttpURLConnection getURL.

Prototype

public URL getURL() 

Source Link

Document

Returns the value of this URLConnection 's URL field.

Usage

From source file:dk.dr.radio.net.Diverse.java

/**
   * Tjek for om vi er p et netvrk der krver login eller lignende.
   * Se 'Handling Network Sign-On' i http://developer.android.com/reference/java/net/HttpHttpURLConnection.html
   *///  w  w w . j  a  v  a2s  .  c om
  private static void tjekOmdirigering(URL u, HttpURLConnection urlConnection) throws IOException {
      URL u2 = urlConnection.getURL();
      if (!u.getHost().equals(u2.getHost())) {
          // Vi blev omdirigeret
          Log.d("tjekOmdirigering " + u);
          Log.d("tjekOmdirigering " + u2);
          //Log.rapporterFejl(omdirigeringsfejl);
          throw new UnknownHostException("Der blev omdirigeret fra " + u.getHost() + " til " + u2.getHost());
      }
  }

From source file:org.rapidcontext.app.plugin.http.HttpPostProcedure.java

/**
 * Logs the HTTP request to the procedure call context.
 *
 * @param cx             the procedure call context
 * @param con            the HTTP connection
 * @param data           the HTTP request data
 *///www.j  a  va 2 s. co m
private static void logRequest(CallContext cx, HttpURLConnection con, String data) {

    cx.log("HTTP " + con.getRequestMethod() + " " + con.getURL());
    Iterator iter = con.getRequestProperties().keySet().iterator();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        cx.log("  " + key + ": " + con.getRequestProperty(key));
    }
    if (data != null) {
        cx.log(data);
    }
}

From source file:ee.ria.xroad.signer.certmanager.OcspClient.java

static OCSPResp fetchResponse(String responderURI, X509Certificate subject, X509Certificate issuer,
        PrivateKey signerKey, X509Certificate signer, String signAlgoId) throws Exception {
    HttpURLConnection connection = createConnection(responderURI);

    OCSPReq ocspRequest = createRequest(subject, issuer, signerKey, signer, signAlgoId);

    log.debug("Fetching certificate '{}' status from responder: {}", subject.getIssuerX500Principal(),
            connection.getURL());

    sendRequest(connection, ocspRequest);
    verifyResponseCode(connection);//from   w w w .j a  v  a 2s  .c om

    byte[] responseData = getResponseData(connection);
    OCSPResp response = parseResponse(responseData);

    verifyResponse(response);

    return response;
}

From source file:com.wifiafterconnect.ParsedHttpInput.java

public static void showRequestProperties(Worker context, HttpURLConnection conn) {
    Map<String, List<String>> reqProps = conn.getRequestProperties();
    context.debug("RequestProperties for [" + conn.getURL() + "]");
    for (String key : reqProps.keySet()) {
        String propStr = "RequestPropery[" + key + "] = {";
        for (String val : reqProps.get(key)) {
            propStr += "[" + val + "]";
        }//from  w  w w.j a  v  a 2s  . c  o  m
        context.debug(propStr + "}");
    }
}

From source file:net.ftb.util.AppUtils.java

public static void debugConnection(URLConnection c, boolean forceDebug) {
    if (Settings.getSettings().getDebugLauncher() || forceDebug) {
        if (!(c instanceof HttpURLConnection)) {
            Logger.logDebug("Something bad just happened.");
        }/*w ww.  j  ava  2  s .  c om*/

        // for IP we need to use reflection or pass url here and rely on dns caching
        // ref: https://community.oracle.com/thread/2149226

        HttpURLConnection conn = (HttpURLConnection) c;
        int responseCode;
        try {
            responseCode = conn.getResponseCode();
        } catch (Exception e) {
            responseCode = -1;
            Logger.logDebug("failed", e);
        }

        Logger.logDebug("Request type: " + conn.getRequestMethod());
        Logger.logDebug("URL: " + conn.getURL());
        Logger.logDebug("Response code: " + responseCode);
        Logger.logDebug("Headers:\n" + AppUtils.MapListToString(conn.getHeaderFields()));
        Logger.logDebug("Message body\n" + AppUtils.ConnectionToString(conn));
        if (conn.getURL().toString().contains("ftb.cursecdn.com")) {
            DownloadUtils.CloudFlareInspector("http://ftb.cursecdn.com/", true);
        }
    }
}

From source file:org.coffeeking.controller.service.util.ConnectedCupServiceUtils.java

public static String readResponseFromGetRequest(HttpURLConnection httpConnection)
        throws DeviceManagementException {
    BufferedReader bufferedReader;
    try {//from www .  j  av  a 2  s.  c o  m
        bufferedReader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
    } catch (IOException e) {
        String errorMsg = "There is an issue with connecting the reader to the input stream at: "
                + httpConnection.getURL();
        log.error(errorMsg);
        throw new DeviceManagementException(errorMsg, e);
    }

    String responseLine;
    StringBuilder completeResponse = new StringBuilder();

    try {
        while ((responseLine = bufferedReader.readLine()) != null) {
            completeResponse.append(responseLine);
        }
    } catch (IOException e) {
        String errorMsg = "Error occured whilst trying read from the connection stream at: "
                + httpConnection.getURL();
        log.error(errorMsg);
        throw new DeviceManagementException(errorMsg, e);
    }
    try {
        bufferedReader.close();
    } catch (IOException e) {
        log.error("Could not succesfully close the bufferedReader to the connection at: "
                + httpConnection.getURL());
    }

    return completeResponse.toString();
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java

protected static String readHttpResponse(HttpURLConnection httpConnection)
        throws OpenTSDBException, IOException {
    String result = "";
    int responseCode = httpConnection.getResponseCode();

    if (responseCode == 200) {
        result = readHTTPConnection(httpConnection);
    } else if (responseCode == 204) {
        result = String.valueOf(responseCode);
    } else {//from   w w  w. j a v a  2 s.c o m
        throw new OpenTSDBException(responseCode, httpConnection.getURL().toString(), "");
    }
    httpConnection.disconnect();

    return result;
}

From source file:uk.org.rivernile.edinburghbustracker.android.Application.java

/**
 * Download the stop database from the server and put it in the
 * application's working data directory.
 *
 * @param context The context to use this method with.
 * @param url The URL of the bus stop database to download.
 *//*from   www . ja  v  a2s.co  m*/
private static void updateStopsDB(final Context context, final String url, final String checksum) {
    if (context == null || url == null || url.length() == 0 || checksum == null || checksum.length() == 0)
        return;
    try {
        // Connect to the server.
        final URL u = new URL(url);
        final HttpURLConnection con = (HttpURLConnection) u.openConnection();
        final InputStream in = con.getInputStream();

        // Make sure the URL is what we expect.
        if (!u.getHost().equals(con.getURL().getHost())) {
            in.close();
            con.disconnect();
            return;
        }

        // The location the file should be downloaded to.
        final File temp = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME + "_temp");
        // The eventual destination of the file.
        final File dest = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME);
        final FileOutputStream out = new FileOutputStream(temp);

        // Get the file from the server.
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        // Make sure the stream is flushed then close resources and
        // disconnect.
        out.flush();
        out.close();
        in.close();
        con.disconnect();

        // Do a MD5 checksum on the downloaded file. Make sure it matches
        // what the server reported.
        if (!md5Checksum(temp).equalsIgnoreCase(checksum)) {
            // If it doesn't match, delete the downloaded file.
            temp.delete();
            return;
        }

        try {
            // Open the temp database and execute the index operation on it.
            final SQLiteDatabase db = SQLiteDatabase.openDatabase(temp.getAbsolutePath(), null,
                    SQLiteDatabase.OPEN_READWRITE);
            BusStopDatabase.setUpIndexes(db);
            db.close();
        } catch (SQLiteException e) {
            // If we couldn't create the index, continue anyway. The user
            // will still be able to use the database, it will just run
            // slowly if they want route lines.
        }

        // Close a currently open database. Delete the old database then
        // move the downloaded file in to its place. Do this while
        // synchronized to make sure noting else uses the database in this
        // time.
        final BusStopDatabase bsd = BusStopDatabase.getInstance(context.getApplicationContext());
        synchronized (bsd) {
            try {
                bsd.getReadableDatabase().close();
            } catch (SQLiteException e) {
                // Nothing to do here. Assume it's already closed.
            }

            dest.delete();
            temp.renameTo(dest);
        }

        // Delete the associated journal file because we no longer need it.
        final File journalFile = context.getDatabasePath(BusStopDatabase.STOP_DB_NAME + "_temp-journal");
        if (journalFile.exists())
            journalFile.delete();

        // Alert the user that the database has been updated.
        Looper.prepare();
        Toast.makeText(context, R.string.bus_stop_db_updated, Toast.LENGTH_LONG).show();
        Looper.loop();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }
}

From source file:org.wso2.carbon.device.mgt.iot.transport.TransportUtils.java

/**
 * This is a utility method that reads and returns the response from a HTTP connection
 *
 * @param httpConnection the connection from which a response is expected
 * @return the response (as a string) from the given HTTP connection
 * @throws TransportHandlerException if any errors occur whilst reading the response from
 *                                   the connection stream
 *//*from  w  w  w. ja v a2s  .  co m*/
public static String readResponseFromHttpRequest(HttpURLConnection httpConnection)
        throws TransportHandlerException {
    BufferedReader bufferedReader;
    try {
        bufferedReader = new BufferedReader(
                new InputStreamReader(httpConnection.getInputStream(), StandardCharsets.UTF_8));
    } catch (IOException exception) {
        String errorMsg = "There is an issue with connecting the reader to the input stream at: "
                + httpConnection.getURL();
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, exception);
    }

    String responseLine;
    StringBuilder completeResponse = new StringBuilder();

    try {
        while ((responseLine = bufferedReader.readLine()) != null) {
            completeResponse.append(responseLine);
        }
    } catch (IOException exception) {
        String errorMsg = "Error occured whilst trying read from the connection stream at: "
                + httpConnection.getURL();
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, exception);
    }
    try {
        bufferedReader.close();
    } catch (IOException exception) {
        log.error("Could not succesfully close the bufferedReader to the connection at: "
                + httpConnection.getURL());
    }
    return completeResponse.toString();
}

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.transport.TransportUtils.java

/**
 * This is a utility method that reads and returns the response from a HTTP connection
 *
 * @param httpConnection the connection from which a response is expected
 * @return the response (as a string) from the given HTTP connection
 * @throws TransportHandlerException if any errors occur whilst reading the response from
 *                                       the connection stream
 *///from w ww . j a va2 s  .c o  m
public static String readResponseFromHttpRequest(HttpURLConnection httpConnection)
        throws TransportHandlerException {
    BufferedReader bufferedReader;
    try {
        bufferedReader = new BufferedReader(
                new InputStreamReader(httpConnection.getInputStream(), StandardCharsets.UTF_8));
    } catch (IOException exception) {
        String errorMsg = AgentConstants.LOG_APPENDER
                + "There is an issue with connecting the reader to the input stream at: "
                + httpConnection.getURL();
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, exception);
    }

    String responseLine;
    StringBuilder completeResponse = new StringBuilder();

    try {
        while ((responseLine = bufferedReader.readLine()) != null) {
            completeResponse.append(responseLine);
        }
    } catch (IOException exception) {
        String errorMsg = AgentConstants.LOG_APPENDER
                + "Error occured whilst trying read from the connection stream at: " + httpConnection.getURL();
        log.error(errorMsg);
        throw new TransportHandlerException(errorMsg, exception);
    }
    try {
        bufferedReader.close();
    } catch (IOException exception) {
        log.error(AgentConstants.LOG_APPENDER
                + "Could not succesfully close the bufferedReader to the connection " + "at: "
                + httpConnection.getURL());
    }
    return completeResponse.toString();
}