Example usage for java.net URLConnection setDoInput

List of usage examples for java.net URLConnection setDoInput

Introduction

In this page you can find the example usage for java.net URLConnection setDoInput.

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

Usage

From source file:XmlUtils.java

public static Document parse(URL url) throws DocumentException, IOException {
    URLConnection urlConnection;
    DataInputStream inStream;/* ww w .  j  a  v a2 s . co m*/
    urlConnection = url.openConnection();
    ((HttpURLConnection) urlConnection).setRequestMethod("GET");

    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(false);
    urlConnection.setUseCaches(false);
    inStream = new DataInputStream(urlConnection.getInputStream());

    byte[] bytes = new byte[1024];
    int read;
    StringBuilder builder = new StringBuilder();
    while ((read = inStream.read(bytes)) >= 0) {
        String readed = new String(bytes, 0, read, "UTF-8");
        builder.append(readed);
    }
    SAXReader reader = new SAXReader();

    XmlUtils.createIgnoreErrorHandler(reader);
    //        InputSource inputSource = new InputSource(new InputStreamReader(inStream, "UTF-8"));
    //        inputSource.setEncoding("UTF-8");
    Document dom = reader.read(new StringReader(builder.toString()));
    inStream.close();
    //        new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("retrieval.xml"), "UTF-8")
    return dom;
}

From source file:com.buglabs.dragonfly.util.WSHelper.java

/**
 * @param url// w w  w .ja  v  a2 s  .  co  m
 * @param inputStream
 * @return
 * @throws IOException
 */
protected static String post(URL url, InputStream inputStream) throws IOException {
    URLConnection connection = url.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);

    OutputStream stream = connection.getOutputStream();
    writeTo(stream, inputStream);
    stream.flush();
    stream.close();

    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line, resp = new String("");
    while ((line = rd.readLine()) != null) {
        resp = resp + line + "\n";
    }
    rd.close();
    is.close();

    return resp;
}

From source file:com.adrguides.utils.HTTPUtils.java

public static InputStream openAddress(Context context, URL url) throws IOException {
    if ("file".equals(url.getProtocol()) && url.getPath().startsWith("/android_asset/")) {
        return context.getAssets().open(url.getPath().substring(15)); // "/android_asset/".length() == 15
    } else {//w  ww. j a v a  2  s . c  om
        URLConnection urlconn = url.openConnection();
        urlconn.setReadTimeout(10000 /* milliseconds */);
        urlconn.setConnectTimeout(15000 /* milliseconds */);
        urlconn.setAllowUserInteraction(false);
        urlconn.setDoInput(true);
        urlconn.setDoOutput(false);
        if (urlconn instanceof HttpURLConnection) {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responsecode = connection.getResponseCode();
            if (responsecode != HttpURLConnection.HTTP_OK) {
                throw new IOException("Http response code returned:" + responsecode);
            }
        }
        return urlconn.getInputStream();
    }
}

From source file:ru.codeinside.gses.webui.form.JsonForm.java

static String loadTemplate(ActivitiApp app, String ref) {
    try {//from   w w  w .  j a  va  2 s .  c om
        URL serverUrl = app.getServerUrl();
        URL url = new URL(serverUrl, ref);
        logger().info("fetch template " + url);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(false);
        connection.setDoInput(true);
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setUseCaches(false);
        connection.connect();
        return Streams.toString(connection.getInputStream());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:UploadUtils.ImgurUpload.java

/**
 * Connect to image host./*from  www.  j  av a2 s .  co m*/
 * @return the connection
 * @throws java.MalformedURLExceptionMalformedURLException if the URL can't be constructed successfully
 * @throws java.IOException if failed to open connection to the newly constructed URL
 */
private static URLConnection connect() throws MalformedURLException, IOException {
    URLConnection conn = null;
    try {
        // opens connection and sends data
        URL url = new URL(IMGUR_POST_URI);
        conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Authorization", "Client-ID " + IMGUR_API_KEY);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    } catch (MalformedURLException ex) {
        throw ex;
    } catch (IOException ex) {
        throw ex;
    }
    return conn;
}

From source file:info.magnolia.cms.exchange.simple.Transporter.java

/**
 * http form multipart form post/*w  w w  .j  a  v  a  2 s.  c  om*/
 * @param connection
 * @param activationContent
 * @throws ExchangeException
 */
public static void transport(URLConnection connection, ActivationContent activationContent)
        throws ExchangeException {
    FileInputStream fis = null;
    DataOutputStream outStream = null;
    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + BOUNDARY);
        connection.setRequestProperty("Cache-Control", "no-cache");

        outStream = new DataOutputStream(connection.getOutputStream());
        outStream.writeBytes("--" + BOUNDARY + "\r\n");

        // set all resources from activationContent
        Iterator fileNameIterator = activationContent.getFiles().keySet().iterator();
        while (fileNameIterator.hasNext()) {
            String fileName = (String) fileNameIterator.next();
            fis = new FileInputStream(activationContent.getFile(fileName));
            outStream.writeBytes("content-disposition: form-data; name=\"" + fileName + "\"; filename=\""
                    + fileName + "\"\r\n");
            outStream.writeBytes("content-type: application/octet-stream" + "\r\n\r\n");
            while (true) {
                synchronized (buffer) {
                    int amountRead = fis.read(buffer);
                    if (amountRead == -1) {
                        break;
                    }
                    outStream.write(buffer, 0, amountRead);
                }
            }
            fis.close();
            outStream.writeBytes("\r\n" + "--" + BOUNDARY + "\r\n");
        }
        outStream.flush();
        outStream.close();

        log.debug("Activation content sent as multipart/form-data");
    } catch (Exception e) {
        throw new ExchangeException(
                "Simple exchange transport failed: " + ClassUtils.getShortClassName(e.getClass()), e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.error("Exception caught", e);
            }
        }
        if (outStream != null) {
            try {
                outStream.close();
            } catch (IOException e) {
                log.error("Exception caught", e);
            }
        }
    }

}

From source file:net.daboross.bukkitdev.skywars.gist.GistReport.java

public static String gistText(Logger logger, String text) {
    URL postUrl;/*w  w w.java  2  s .  c  o m*/
    try {
        postUrl = new URL("https://api.github.com/gists");
    } catch (MalformedURLException ex) {
        logger.log(Level.FINE, "Non severe error encoding api.github.com URL", ex);
        return null;
    }
    URLConnection connection;
    try {
        connection = postUrl.openConnection();
    } catch (IOException ex) {
        logger.log(Level.FINE, "Non severe error opening api.github.com connection", ex);
        return null;
    }
    connection.setDoOutput(true);
    connection.setDoInput(true);
    JSONStringer outputJson = new JSONStringer();
    try {
        outputJson.object().key("description").value("SkyWars debug").key("public").value("false").key("files")
                .object().key("report.md").object().key("content").value(text).endObject().endObject()
                .endObject();
    } catch (JSONException ex) {
        logger.log(Level.FINE, "Non severe error while writing report", ex);
        return null;
    }
    String jsonOuptutString = outputJson.toString();
    try (OutputStream outputStream = connection.getOutputStream()) {
        try (OutputStreamWriter requestWriter = new OutputStreamWriter(outputStream)) {
            requestWriter.append(jsonOuptutString);
            requestWriter.close();
        }
    } catch (IOException ex) {
        logger.log(Level.FINE, "Non severe error writing report", ex);
        return null;
    }

    JSONObject inputJson;
    try {
        inputJson = new JSONObject(readConnection(connection));
    } catch (JSONException | IOException unused) {
        logger.log(Level.FINE, "Non severe error while reading response for report.", unused);
        return null;
    }
    String resultUrl = inputJson.optString("html_url", null);
    return resultUrl == null ? null : shortenURL(logger, resultUrl);
}

From source file:org.apache.niolex.commons.net.DownloadUtil.java

/**
 * Download the file pointed by the url and return the content as byte array.
 *
 * @param strUrl/*from   w  ww.  j  a va  2  s  .co  m*/
 *            The Url to be downloaded.
 * @param connectTimeout
 *            Connect timeout in milliseconds.
 * @param readTimeout
 *            Read timeout in milliseconds.
 * @param maxFileSize
 *            Max file size in BYTE.
 * @param useCache Whether we use thread local cache or not.
 * @return The file content as byte array.
 * @throws NetException
 */
public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize,
        Boolean useCache) throws NetException {
    LOG.debug("Start to download file [{}], C{}R{}M{}.", strUrl, connectTimeout, readTimeout, maxFileSize);
    InputStream in = null;
    try {
        URL url = new URL(strUrl); // We use Java URL to download file.
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        ucon.setDoOutput(false);
        ucon.setDoInput(true);
        ucon.connect();
        final int contentLength = ucon.getContentLength();
        validateContentLength(strUrl, contentLength, maxFileSize);
        if (ucon instanceof HttpURLConnection) {
            validateHttpCode(strUrl, (HttpURLConnection) ucon);
        }
        in = ucon.getInputStream(); // Get the input stream.
        byte[] ret = null;
        // Create the byte array buffer according to the strategy.
        if (contentLength > 0) {
            ret = commonDownload(contentLength, in);
        } else {
            ret = unusualDownload(strUrl, in, maxFileSize, useCache);
        }
        LOG.debug("Succeeded to download file [{}] size {}.", strUrl, ret.length);
        return ret;
    } catch (NetException e) {
        LOG.info(e.getMessage());
        throw e;
    } catch (Exception e) {
        String msg = "Failed to download file " + strUrl + " msg=" + e.toString();
        LOG.warn(msg);
        throw new NetException(NetException.ExCode.IOEXCEPTION, msg, e);
    } finally {
        // Close the input stream.
        StreamUtil.closeStream(in);
    }
}

From source file:oneDrive.OneDriveAPI.java

public static void uploadFile(String filePath) {
    URLConnection urlconnection = null;
    try {/* www  .  j a va2  s. c  o  m*/
        File file = new File(UPLOAD_PATH + filePath);
        URL url = new URL(DRIVE_PATH + file.getName() + ":/content");
        urlconnection = url.openConnection();
        urlconnection.setDoOutput(true);
        urlconnection.setDoInput(true);

        if (urlconnection instanceof HttpURLConnection) {
            try {
                ((HttpURLConnection) urlconnection).setRequestMethod("PUT");
                ((HttpURLConnection) urlconnection).setRequestProperty("Content-type",
                        "application/octet-stream");
                ((HttpURLConnection) urlconnection).addRequestProperty("Authorization",
                        "Bearer " + ACCESS_TOKEN);
                ((HttpURLConnection) urlconnection).connect();

            } catch (ProtocolException e) {
                e.printStackTrace();
            }
        }

        BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        int i;
        // read byte by byte until end of stream
        while ((i = bis.read()) >= 0) {
            bos.write(i);
        }
        bos.flush();
        bos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:net.pms.util.OpenSubtitle.java

public static String fetchSubs(String url, String outName) throws FileNotFoundException, IOException {
    if (!login()) {
        return "";
    }/*from w  ww.  j ava2 s .c o  m*/
    if (StringUtils.isEmpty(outName)) {
        outName = subFile(String.valueOf(System.currentTimeMillis()));
    }
    File f = new File(outName);
    URL u = new URL(url);
    URLConnection connection = u.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);
    InputStream in = connection.getInputStream();
    OutputStream out;
    try (GZIPInputStream gzipInputStream = new GZIPInputStream(in)) {
        out = new FileOutputStream(f);
        byte[] buf = new byte[4096];
        int len;
        while ((len = gzipInputStream.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    }
    out.close();
    if (!PMS.getConfiguration().isLiveSubtitlesKeep()) {
        int tmo = PMS.getConfiguration().getLiveSubtitlesTimeout();
        if (tmo <= 0) {
            PMS.get().addTempFile(f);
        } else {
            PMS.get().addTempFile(f, tmo);
        }
    }
    return f.getAbsolutePath();
}