Example usage for java.net HttpURLConnection connect

List of usage examples for java.net HttpURLConnection connect

Introduction

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

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java

private static SSLContext sslContext() {
    final String property = SettingsManager.settings().ssl();
    if (property != null && !property.isEmpty() && !"null".equals(property)) {
        if ("trustanything".equals(property)) {
            try {
                return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()),
                        new TrustStrategy() {
                            public boolean isTrusted(X509Certificate[] chain, String authType)
                                    throws CertificateException {
                                return true;
                            }/*from  w  w w  .j a  v  a  2  s.  c o m*/
                        }).build();
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        } else {
            try {
                String location = property;
                location = location.equals("compatible")
                        ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt"
                        : location;
                File cachedPemFile = new File("./pemfile_cached");
                boolean remote = location.startsWith("https://") || location.startsWith("http://");
                if (remote && cachedPemFile.exists()
                        && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) {
                    location = cachedPemFile.getAbsolutePath();
                    remote = false;
                }
                String pemBlocks = null;
                if (remote) {
                    HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler
                            .defaultConnection(new URL(location));
                    remotePemFile.setRequestMethod("GET");
                    remotePemFile.connect();
                    pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile));
                    cachedPemFile.delete();
                    Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8"));
                } else {
                    pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())),
                            "utf-8");
                }
                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(null);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Matcher matcher = pemBlock.matcher(pemBlocks);
                boolean found = false;
                while (matcher.find()) {
                    String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", "");
                    ByteArrayInputStream byteStream = new ByteArrayInputStream(
                            Base64.getDecoder().decode(pemBlock));
                    java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf
                            .generateCertificate(byteStream);
                    String alias = cert.getSubjectX500Principal().getName("RFC2253");
                    if (alias != null && !keyStore.containsAlias(alias)) {
                        found = true;
                        keyStore.setCertificateEntry(alias, cert);
                    }
                }
                if (found) {
                    KeyManagerFactory keyManager = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManager.init(keyStore, null);
                    TrustManagerFactory trustManager = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    trustManager.init(keyStore);
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
                    return context;
                }
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        }
    }
    return SSLContexts.createSystemDefault();
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Delete specified dataset/*  ww  w  . jav a 2 s  .c o m*/
 * 
 * @param dataSetName
 * @throws IOException
 * @throws HttpException
 */
public static void deleteDataSet(@NonNull String dataSetName) throws IOException, HttpException {
    logger.info("delete dataset: " + dataSetName);

    URL url = new URL(HOST + "/$/datasets/" + dataSetName);
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("DELETE");
    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_OK:
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }
}

From source file:outfox.dict.contest.util.FileUtils.java

/**
 * ??/* w ww.j  a v a 2s . co  m*/
 * @param downloadUrl
 * @return
 */
public static byte[] getbytesFromURL(String downloadUrl) {
    HttpURLConnection httpUrl = null;
    ByteArrayOutputStream out = null;
    byte[] byteArray = null;
    InputStream in = null;
    try {
        // 
        URL url = new URL(downloadUrl);
        httpUrl = (HttpURLConnection) url.openConnection();
        // ?
        httpUrl.connect();
        // ??
        in = httpUrl.getInputStream();

        out = new ByteArrayOutputStream();
        byte[] b = new byte[4096];
        int n;
        while ((n = in.read(b)) != -1) {
            out.write(b, 0, n);
        }
        byteArray = out.toByteArray();
        in.close();
        out.close();
        httpUrl.disconnect();
    } catch (Exception e) {
        LOG.error("FileUtils.getBytesFromURL error...", e);
    }
    return byteArray;
}

From source file:mashberry.com500px.util.Api_Parser.java

/*******************************************************************************
  * /*w  w w . j  a v  a 2s .com*/
  *    (  )
  * 
  *******************************************************************************/
public static String get_first_detail(final String url_feature, final int url_image_size,
        final String url_category, final int url_page, int image_no) {
    String returnStr = "success";
    String urlStr = DB.Get_Photo_Url + "?feature=" + url_feature + "&image_size=" + url_image_size + "&only="
            + getCategoryName(url_category) + "&page=" + url_page + "&consumer_key=" + Var.consumer_key
            + "&rpp=" + image_no;

    try {
        URL url = new URL(urlStr);
        URLConnection uc = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) uc;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setConnectTimeout(10000);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        int response = httpConn.getResponseCode();
        Main.progressBar_process(50);

        if (response == HttpURLConnection.HTTP_OK) {
            InputStream in = httpConn.getInputStream();
            String smallImageOpt = "3"; //      (8 1/8  )
            String largeImageOpt = "0";
            String userPictureOpt = "8";
            String result = convertStreamToString(in);
            JSONObject jObject = new JSONObject(result);
            JSONArray jsonArray = jObject.getJSONArray("photos");
            Main.progressBar_process(75);

            if (jsonArray.length() == 0) {
                returnStr = "no results";
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    Var.categoryArr.add(jsonArray.getJSONObject(i).getString("category"));
                    Var.idArr.add(jsonArray.getJSONObject(i).getString("id"));
                    String smallImage = jsonArray.getJSONObject(i).getString("image_url");
                    String largeImage = largeImageOpt
                            + smallImage.substring(0, smallImage.lastIndexOf(".jpg") - 1) + "4.jpg";
                    Var.imageSmall_urlArr.add(smallImageOpt + smallImage);
                    Var.imageLarge_urlArr.add(largeImage);
                    Var.nameArr.add(jsonArray.getJSONObject(i).getString("name"));
                    Var.ratingArr.add(jsonArray.getJSONObject(i).getString("rating"));

                    JSONObject jsonuser = jsonArray.getJSONObject(i).getJSONObject("user");
                    Var.user_firstnameArr.add(jsonuser.getString("firstname"));
                    Var.user_fullnameArr.add(jsonuser.getString("fullname"));
                    Var.user_lastnameArr.add(jsonuser.getString("lastname"));
                    Var.user_upgrade_statusArr.add(jsonuser.getString("upgrade_status"));
                    Var.user_usernameArr.add(jsonuser.getString("username"));
                    Var.user_userpic_urlArr.add(userPictureOpt + jsonuser.getString("userpic_url"));

                    Main.progressBar_process(75 + (15 * i / jsonArray.length()));
                }
            }

            //            Log.i("Main", "urlStr   " +urlStr);
            //            Log.i("Main", "url_feature   " +url_feature);
            //            Log.i("Main", "categoryArr   " +Var.categoryArr);
            //            Log.i("Main", "idArr   " +Var.idArr);
            //            Log.i("Main", "imageLarge_urlArr   " +Var.imageLarge_urlArr);
            //            Log.i("Main", "nameArr   " +Var.nameArr);
            //            Log.i("Main", "ratingArr   " +Var.ratingArr);
            //            Log.i("Main", "user_firstnameArr   " +Var.user_firstnameArr);
            //            Log.i("Main", "user_fullnameArr   " +Var.user_fullnameArr);
            //            Log.i("Main", "user_lastnameArr   " +Var.user_lastnameArr);
            //            Log.i("Main", "user_upgrade_statusArr   " +Var.user_upgrade_statusArr);
            //            Log.i("Main", "user_usernameArr   " +Var.user_usernameArr);
            //            Log.i("Main", "user_userpic_urlArr   " +Var.user_userpic_urlArr);
        } else {
            returnStr = "not response";
            return returnStr;
        }
    } catch (Exception e) {
        e.printStackTrace();
        returnStr = "not response";
        return returnStr;
    }
    return returnStr;
}

From source file:com.github.terma.m.node.Node.java

private static void send(final String serverHost, final int serverPort, final String context,
        final List<Event> events) throws IOException {
    final HttpURLConnection connection = (HttpURLConnection) new URL("http", serverHost, serverPort,
            context + "/node").openConnection();
    connection.setDoOutput(true);/*from   w w  w  . j  a  v a 2 s .co m*/
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/json");
    connection.setRequestProperty("charset", "utf-8");
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);
    connection.connect();
    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(new Gson().toJson(events).getBytes());
    connection.getInputStream().read();
    outputStream.close();
}

From source file:net.andylizi.colormotd.utils.AttributionUtil.java

private static String sendGet(String url, String param, String charset) {
    StringBuilder result = new StringBuilder(1024);
    BufferedReader in = null;/*from   ww w.j a v a  2s .  c  o m*/
    try {
        String urlNameString = url + "?" + param;
        URL realUrl = new URL(urlNameString);
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        conn.setRequestProperty("User-Agent", "ColorMOTD/" + UUID.randomUUID());
        conn.setRequestProperty("Accept-Charset", charset);
        conn.setUseCaches(true);
        conn.setConnectTimeout(2000);
        conn.setReadTimeout(3000);
        conn.connect();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName(charset)), 1024);
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
        conn.disconnect();
    } catch (Exception e) {
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e2) {
        }
    }
    return result.toString();
}

From source file:net.dian1.player.download.DownloadTask.java

public static Boolean downloadFile(DownloadJob job) throws IOException {

    // TODO rewrite to apache client

    PlaylistEntry mPlaylistEntry = job.getPlaylistEntry();
    String mDestination = job.getDestination();

    Music engineMusic = mPlaylistEntry.getMusic();
    String url = engineMusic.getFirstMusicNetUrl();

    if (TextUtils.isEmpty(url)) {
        engineMusic = requestMusicDetail(engineMusic.getId());
        url = engineMusic.getFirstMusicNetUrl();
        job.getPlaylistEntry().setMusic(engineMusic);
    }/*  w  w  w.  j a v a  2 s . c o  m*/

    //url = "http://room2.5dian1.net/??1/15.?.mp3";
    if (TextUtils.isEmpty(url)) {
        return false;
    }
    URL u = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
    connection.setRequestMethod("GET");
    //c.setDoOutput(true);
    //c.setDoInput(true);
    connection.setRequestProperty("Accept", "*/*");
    connection.setRequestProperty("Content-Type", "audio/mpeg");
    connection.connect();
    job.setTotalSize(connection.getContentLength());

    Log.i(Dian1Application.TAG, "creating file");

    String path = DownloadHelper.getAbsolutePath(mPlaylistEntry, mDestination);
    String fileName = DownloadHelper.getFileName(mPlaylistEntry, job.getFormat());

    try {
        // Create multiple directory
        boolean success = (new File(path)).mkdirs();
        if (success) {
            Log.i(Dian1Application.TAG, "Directory: " + path + " created");
        }

    } catch (Exception e) {//Catch exception if any
        Log.e(Dian1Application.TAG, "Error creating folder", e);
        return false;
    }

    File outFile = new File(path, fileName);

    FileOutputStream fos = new FileOutputStream(outFile);

    InputStream in = connection.getInputStream();

    if (in == null) {
        // When InputStream is a NULL
        fos.close();
        return false;
    }

    byte[] buffer = new byte[1024];
    int lenght = 0;
    while ((lenght = in.read(buffer)) > 0) {
        fos.write(buffer, 0, lenght);
        job.setDownloadedSize(job.getDownloadedSize() + lenght);
    }
    fos.close();

    mPlaylistEntry.getMusic().getFirstMusicUrlInfo().setLocalUrl(outFile.getAbsolutePath());
    //downloadCover(job);
    return true;
}

From source file:ee.ria.xroad.common.util.CertHashBasedOcspResponderClient.java

/**
 * Creates a GET request to the internal cert hash based OCSP responder and expects OCSP responses.
 *
 * @param destination URL of the OCSP response provider
 * @return list of OCSP response objects
 * @throws IOException   if I/O errors occurred
 * @throws OCSPException if the response could not be parsed
 *//*  www .ja va2s .c om*/
public static List<OCSPResp> getOcspResponsesFromServer(URL destination) throws IOException, OCSPException {
    HttpURLConnection connection = (HttpURLConnection) destination.openConnection();
    connection.setRequestProperty("Accept", MimeTypes.MULTIPART_RELATED);
    connection.setDoOutput(true);
    connection.setConnectTimeout(SystemProperties.getOcspResponderClientConnectTimeout());
    connection.setReadTimeout(SystemProperties.getOcspResponderClientReadTimeout());
    connection.setRequestMethod(METHOD);
    connection.connect();

    if (!VALID_RESPONSE_CODES.contains(connection.getResponseCode())) {
        log.error("Invalid HTTP response ({}) from responder: {}", connection.getResponseCode(),
                connection.getResponseMessage());

        throw new IOException(connection.getResponseMessage());
    }

    MimeConfig config = new MimeConfig.Builder().setHeadlessParsing(connection.getContentType()).build();

    final List<OCSPResp> responses = new ArrayList<>();
    final MimeStreamParser parser = new MimeStreamParser(config);

    parser.setContentHandler(new AbstractContentHandler() {
        @Override
        public void startMultipart(BodyDescriptor bd) {
            parser.setFlat();
        }

        @Override
        public void body(BodyDescriptor bd, InputStream is) throws MimeException, IOException {
            if (bd.getMimeType().equalsIgnoreCase(MimeTypes.OCSP_RESPONSE)) {
                responses.add(new OCSPResp(IOUtils.toByteArray(is)));
            }
        }
    });

    try {
        parser.parse(connection.getInputStream());
    } catch (MimeException e) {
        throw new OCSPException("Error parsing response", e);
    }

    return responses;
}

From source file:fr.ms.tomcat.manager.TomcatManagerUrl.java

public static String appelUrl(final URL url, final String username, final String password,
        final String charset) {

    try {/*from ww w .  j  ava  2s. co  m*/
        final URLConnection urlTomcatConnection = url.openConnection();

        final HttpURLConnection connection = (HttpURLConnection) urlTomcatConnection;

        LOG.debug("url : " + url);
        connection.setAllowUserInteraction(false);
        connection.setDoInput(true);
        connection.setUseCaches(false);

        connection.setDoOutput(false);
        connection.setRequestMethod("GET");

        connection.setRequestProperty("Authorization", toAuthorization(username, password));

        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new TomcatManagerException("Reponse http : " + connection.getResponseMessage()
                        + " - Les droits \"manager\" ne sont pas appliques - utilisateur : \"" + username
                        + "\" password : \"" + password + "\"");
            }
            throw new TomcatManagerException("HttpURLConnection.HTTP_UNAUTHORIZED");
        }

        final String response = toString(connection.getInputStream(), charset);

        LOG.debug("reponse : " + response);

        return response;
    } catch (final Exception e) {
        throw new TomcatManagerException("L'url du manager tomcat est peut etre incorrecte : \"" + url + "\"",
                e);
    }
}

From source file:a122016.rr.com.alertme.QueryUtilsPoliceStation.java

/**
 * Make an HTTP request to the given URL and return a String as the response.
 *///from ww  w.  j av a  2  s .  c o  m
private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // If the request was successful (response code 200),
        // then read the input stream and parse the response.
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving the PoliceStations JSON results.", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            // Closing the input stream could throw an IOException, which is why
            // the makeHttpRequest(URL url) method signature specifies than an IOException
            // could be thrown.
            inputStream.close();
        }
    }
    return jsonResponse;
}