Example usage for java.net HttpURLConnection getInputStream

List of usage examples for java.net HttpURLConnection getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:com.adanac.module.blog.api.HttpApiHelper.java

public static void baiduPush(int remain) {
    String pushUrl = DaoFactory.getDao(HtmlPageDao.class).findPushUrl();
    if (pushUrl == null) {
        if (logger.isInfoEnabled()) {
            logger.info("all html page has been pushed!");
        }//w  w w.  j av a  2  s  .c  o  m
        return;
    }
    if (remain <= 0) {
        if (logger.isInfoEnabled()) {
            logger.info("there has no remain[" + remain + "]!");
        }
        return;
    }
    if (logger.isInfoEnabled()) {
        logger.info("find push url : " + pushUrl);
    }
    String url = "http://data.zz.baidu.com/urls?site=" + site + "&token=" + token;
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(pushUrl.getBytes("UTF-8"));
        outputStream.write("\r\n".getBytes("UTF-8"));
        outputStream.flush();
        int status = connection.getResponseCode();
        if (logger.isInfoEnabled()) {
            logger.info("baidu-push response code : " + status);
        }
        if (status == HttpServletResponse.SC_OK) {
            String response = IOUtil.read(connection.getInputStream());
            if (logger.isInfoEnabled()) {
                logger.info("baidu-push response : " + response);
            }
            JSONObject result = JSONObject.fromObject(response);
            if (result.getInt("success") >= 1) {
                DaoFactory.getDao(HtmlPageDao.class).updateIsPush(pushUrl);
            } else {
                logger.warn("push url failed : " + pushUrl);
            }
            baiduPush(result.getInt("remain"));
        } else {
            logger.error("baidu-push error : " + IOUtil.read(connection.getErrorStream()));
        }
    } catch (Exception e) {
        logger.error("baidu push failed ...", e);
    }
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * /*  w  ww .  j  a  v  a  2  s.  c  o  m*/
 *
 * @param media_id ?ID
 * @param identity 
 * @param filepath ?(????)
 * @return ?(???)error
 */
public static String downLoadMediaFile(String requestUrl, String media_id, String identity, String filepath) {
    String mediaLocalURL = "error";
    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    DataOutputStream dataOutputStream = null;
    try {
        URL downLoadURL = new URL(requestUrl);
        // URL
        HttpURLConnection connection = (HttpURLConnection) downLoadURL.openConnection();
        //?
        connection.setRequestMethod("GET");
        // 
        connection.connect();
        //?,?text,json
        if (connection.getContentType().equalsIgnoreCase("text/plain")) {
            // BufferedReader???URL?
            inputStream = connection.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_CHARSET));
            String valueString = null;
            StringBuffer bufferRes = new StringBuffer();
            while ((valueString = read.readLine()) != null) {
                bufferRes.append(valueString);
            }
            inputStream.close();
            String errMsg = bufferRes.toString();
            JSONObject jsonObject = JSONObject.parseObject(errMsg);
            logger.error("???" + (jsonObject.getInteger("errcode")));
            mediaLocalURL = "error";
        } else {
            BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
            String ds = connection.getHeaderField("Content-disposition");
            //??
            String fullName = ds.substring(ds.indexOf("filename=\"") + 10, ds.length() - 1);
            //?--??
            String preffix = fullName.substring(0, fullName.lastIndexOf("."));
            //?
            String suffix = fullName.substring(preffix.length() + 1);
            //
            String length = connection.getHeaderField("Content-Length");
            //
            String type = connection.getHeaderField("Content-Type");
            //
            byte[] buffer = new byte[8192]; // 8k
            int count = 0;
            mediaLocalURL = filepath + File.separator;
            File file = new File(mediaLocalURL);
            if (!file.exists()) {
                file.mkdirs();
            }
            File mediaFile = new File(mediaLocalURL, fullName);
            fileOutputStream = new FileOutputStream(mediaFile);
            dataOutputStream = new DataOutputStream(fileOutputStream);
            while ((count = bis.read(buffer)) != -1) {
                dataOutputStream.write(buffer, 0, count);
            }
            //?
            mediaLocalURL += fullName;
            bis.close();
            dataOutputStream.close();
            fileOutputStream.close();
        }
    } catch (IOException e) {
        logger.error("?", e);
    }
    return mediaLocalURL;
}

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

/**
 * Checks the file for corruption.// ww  w  .j av a2s. co m
 * @param file - File to check
 * @param url - base url to grab md5 with old method
 * @return boolean representing if it is valid
 * @throws IOException 
 */
public static boolean backupIsValid(File file, String url) throws IOException {
    Logger.logInfo("Issue with new md5 method, attempting to use backup method.");
    String content = null;
    Scanner scanner = null;
    String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer()))
            ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer())
            : Locations.masterRepo;
    resolved += "/md5/FTB2/" + url;
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) new URL(resolved).openConnection();
        connection.setRequestProperty("Cache-Control", "no-transform");
        int response = connection.getResponseCode();
        if (response == 200) {
            scanner = new Scanner(connection.getInputStream());
            scanner.useDelimiter("\\Z");
            content = scanner.next();
        }
        if (response != 200 || (content == null || content.isEmpty())) {
            for (String server : backupServers.values()) {
                resolved = "http://" + server + "/md5/FTB2/" + url.replace("/", "%5E");
                connection = (HttpURLConnection) new URL(resolved).openConnection();
                connection.setRequestProperty("Cache-Control", "no-transform");
                response = connection.getResponseCode();
                if (response == 200) {
                    scanner = new Scanner(connection.getInputStream());
                    scanner.useDelimiter("\\Z");
                    content = scanner.next();
                    if (content != null && !content.isEmpty()) {
                        break;
                    }
                }
            }
        }
    } catch (IOException e) {
    } finally {
        connection.disconnect();
        if (scanner != null) {
            scanner.close();
        }
    }
    String result = fileMD5(file);
    Logger.logInfo("Local: " + result.toUpperCase());
    Logger.logInfo("Remote: " + content.toUpperCase());
    return content.equalsIgnoreCase(result);
}

From source file:com.screenslicer.core.util.Email.java

public static void sendResults(EmailExport export) {
    if (WebApp.DEV) {
        return;/*from  w  w  w .  j  a v a  2  s  .  co m*/
    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("key", Config.instance.mandrillKey());
    List<Map<String, String>> to = new ArrayList<Map<String, String>>();
    for (int i = 0; i < export.recipients.length; i++) {
        to.add(CommonUtil.asMap("email", "name", "type", export.recipients[i],
                export.recipients[i].split("@")[0], "to"));
    }
    List<Map<String, String>> attachments = new ArrayList<Map<String, String>>();
    for (Map.Entry<String, byte[]> entry : export.attachments.entrySet()) {
        attachments.add(CommonUtil.asMap("type", "name", "content", new Tika().detect(entry.getValue()),
                entry.getKey(), Base64.encodeBase64String(entry.getValue())));
    }
    params.put("message", CommonUtil.asObjMap("track_clicks", "track_opens", "html", "text", "headers",
            "subject", "from_email", "from_name", "to", "attachments", false, false, "Results attached.",
            "Results attached.", CommonUtil.asMap("Reply-To", Config.instance.mandrillEmail()), export.title,
            Config.instance.mandrillEmail(), Config.instance.mandrillEmail(), to, attachments));
    params.put("async", true);
    HttpURLConnection conn = null;
    String resp = null;
    Log.info("Sending email: " + export.title, false);
    try {
        conn = (HttpURLConnection) new URL("https://mandrillapp.com/api/1.0/messages/send.json")
                .openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("User-Agent", "Mandrill-Curl/1.0");
        String data = CommonUtil.gson.toJson(params, CommonUtil.objectType);
        byte[] bytes = data.getBytes("utf-8");
        conn.setRequestProperty("Content-Length", "" + bytes.length);
        OutputStream os = conn.getOutputStream();
        os.write(bytes);
        conn.connect();
        resp = IOUtils.toString(conn.getInputStream(), "utf-8");
        if (resp.contains("\"rejected\"") || resp.contains("\"invalid\"")) {
            Log.warn("Invalid/rejected email addreses");
        }
    } catch (Exception e) {
        Log.exception(e);
    }
}

From source file:com.thyn.backend.gcm.GcmSender.java

public static String addDeviceToDeviceGroup(String notification_key_name, String notification_key,
        String registration_token) {
    String resp = null;//from   w w  w  . j a va2s. c o m
    try {
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();

        // Where to send GCM message.
        if (notification_key_name != null && registration_token != null) {
            jGcmData.put("operation", "add");
            jGcmData.put("notification_key_name", notification_key_name.trim());
            jGcmData.put("notification_key", notification_key.trim());
            jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]"));
        } else {
            Logger.logError("Error", new NullPointerException());
            return null;
        }

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/notification");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("project_id", SENDER_ID);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        resp = IOUtils.toString(inputStream);

    } catch (IOException e) {
        Logger.logError("Unable to add Device to Device group.", e);

    }
    return resp;
}

From source file:edu.jhu.cvrg.waveform.utility.WebServiceUtility.java

public static Map<String, String> annotationJSONLookup(String restURL, String... key) {

    Map<String, String> ret = null;
    URL url;//w w  w.ja  v a  2s .c  o m
    HttpURLConnection conn = null;
    try {
        if (System.currentTimeMillis() > waitUntil) {
            url = new URL(restURL);

            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            BufferedReader in = new BufferedReader(new InputStreamReader((conn.getInputStream())));

            String jsonSrc = in.readLine();
            in.close();

            JSONObject jsonObject = new JSONObject(jsonSrc);
            ret = new HashMap<String, String>();

            for (int i = 0; i < key.length; i++) {
                Object atr = jsonObject.get(key[i]);
                String value = "";
                if (atr instanceof JSONArray) {
                    JSONArray array = ((JSONArray) atr);
                    for (int j = 0; j < array.length(); j++) {
                        value += array.getString(j);
                    }
                } else {
                    value = atr.toString();
                }
                if (value.isEmpty()) {
                    value = "No " + key[i] + " found";
                }
                ret.put(key[i], value);
            }
        } else {
            log.warn("Waiting the bioportal server");
        }

    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        //wait for 1 minute
        waitUntil = System.currentTimeMillis() + (1000 * 60);

        log.error(ioe.getMessage());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return ret;
}

From source file:Main.java

/**
 * Do an HTTP POST and return the data as a byte array.
 *//*from ww  w. j  av a  2 s  .  c  om*/
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws MalformedURLException, IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        urlConnection.connect();
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } catch (IOException e) {
        String details;
        if (urlConnection != null) {
            details = "; code=" + urlConnection.getResponseCode() + " (" + urlConnection.getResponseMessage()
                    + ")";
        } else {
            details = "";
        }
        Log.e("ExoplayerUtil", "executePost: Request failed" + details, e);
        throw e;
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.thyn.backend.gcm.GcmSender.java

public static String createDeviceGroup(String notification_key_name, String registration_token) {
    String Response_Notification_Key = null;
    try {//from   ww w  .j  a  va  2  s.  co m
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();

        // Where to send GCM message.
        if (notification_key_name != null && registration_token != null) {
            jGcmData.put("operation", "create");
            jGcmData.put("notification_key_name", notification_key_name.trim());
            jGcmData.put("registration_ids", new JSONArray("[\"" + registration_token + "\"]"));
        } else {
            Logger.logError("Error", new NullPointerException());
            return null;
        }
        Logger.logInfo(jGcmData.toString());

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/notification");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("project_id", SENDER_ID);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        Logger.logInfo("the response from GCM server is: " + resp);
        JSONObject jResp = new JSONObject(resp);
        Response_Notification_Key = jResp.getString("notification_key");

    } catch (IOException e) {
        Logger.logError("Unable to create a device group.", e);

    }
    return Response_Notification_Key;
}

From source file:de.mas.telegramircbot.utils.images.ImgurUploader.java

public static String uploadImageAndGetLink(String clientID, byte[] image) throws IOException {
    URL url;/*from w w w . j av a 2s . c  o  m*/
    url = new URL(Settings.IMGUR_API_URL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    String dataImage = Base64.getEncoder().encodeToString(image);
    String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(dataImage, "UTF-8");

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Client-ID " + clientID);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.connect();
    StringBuilder stb = new StringBuilder();
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        stb.append(line).append("\n");
    }
    wr.close();
    rd.close();

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ImgurResponse.class, new ImgurResponseDeserializer());
    Gson gson = gsonBuilder.create();

    // The JSON data
    try {
        ImgurResponse response = gson.fromJson(stb.toString(), ImgurResponse.class);
        return response.getLink();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return stb.toString();
}

From source file:com.moviejukebox.plugin.OpenSubtitlesPlugin.java

private static boolean subtitleDownload(Movie movie, File movieFile, File subtitleFile) {
    try {//from   w  w w  .j  a v  a  2s.co  m
        String ret;
        String xml;

        String moviehash = getHash(movieFile);
        String moviebytesize = String.valueOf(movieFile.length());

        xml = generateXMLRPCSS(moviehash, moviebytesize);
        ret = sendRPC(xml);

        String subDownloadLink = getValue("SubDownloadLink", ret);

        if (StringUtils.isBlank(subDownloadLink)) {
            String moviefilename = movieFile.getName();

            // Do not search by file name for BD rip files in the format 0xxxx.m2ts
            if (!(moviefilename.toUpperCase().endsWith(".M2TS") && moviefilename.startsWith("0"))) {

                // Try to find the subtitle using file name
                String subfilename = subtitleFile.getName();
                int index = subfilename.lastIndexOf('.');

                String query = subfilename.substring(0, index);

                xml = generateXMLRPCSS(query);
                ret = sendRPC(xml);

                subDownloadLink = getValue("SubDownloadLink", ret);
            }
        }

        if (StringUtils.isBlank(subDownloadLink)) {
            LOG.debug("Subtitle not found for {}", movieFile.getName());
            return Boolean.FALSE;
        }

        LOG.debug("Download subtitle for {}", movie.getBaseName());

        URL url = new URL(subDownloadLink);
        HttpURLConnection connection = (HttpURLConnection) (url
                .openConnection(YamjHttpClientBuilder.getProxy()));
        connection.setRequestProperty("Connection", "Close");

        try (InputStream inputStream = connection.getInputStream()) {
            int code = connection.getResponseCode();
            if (code != HttpURLConnection.HTTP_OK) {
                LOG.error("Download Failed");
                return Boolean.FALSE;
            }
            FileTools.copy(inputStream, new FileOutputStream(subtitleFile));

        } finally {
            connection.disconnect();
        }

        String subLanguageID = getValue("SubLanguageID", ret);
        if (StringUtils.isNotBlank(subLanguageID)) {
            SubtitleTools.addMovieSubtitle(movie, subLanguageID);
        } else {
            SubtitleTools.addMovieSubtitle(movie, "YES");
        }

        return Boolean.TRUE;

    } catch (Exception ex) {
        LOG.error("Download Exception (Movie Not Found)", ex);
        return Boolean.FALSE;
    }

}