Example usage for java.net URLConnection setDoOutput

List of usage examples for java.net URLConnection setDoOutput

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

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

Usage

From source file:nl.ru.ai.projects.parrot.tools.TwitterAccess.java

/**
 * Uploads an image//from   ww w .j  a v a2  s  .c o  m
 * @param image The image to upload
 * @param tweet The text of the tweet that needs to be posted with the image
 */
public void uploadImage(byte[] image, String tweet) {
    if (!enabled)
        return;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    RenderedImage img = getImageFromCamera(image);
    try {
        ImageIO.write(img, "jpg", baos);
        URL url = new URL("http://api.imgur.com/2/upload.json");
        String data = URLEncoder.encode("image", "UTF-8") + "="
                + URLEncoder.encode(Base64.encodeBase64String(baos.toByteArray()), "UTF-8");
        data += "&" + URLEncoder.encode("key", "UTF-8") + "="
                + URLEncoder.encode("f9c4861fc0aec595e4a64dd185751d28", "UTF-8");

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        StringBuffer buffer = new StringBuffer();
        InputStreamReader isr = new InputStreamReader(conn.getInputStream());
        Reader in = new BufferedReader(isr);
        int ch;
        while ((ch = in.read()) > -1)
            buffer.append((char) ch);

        String imgURL = processJSON(buffer.toString());
        setStatus(tweet + " " + imgURL, 100);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

From source file:org.pentaho.reporting.libraries.resourceloader.loader.URLResourceData.java

public InputStream getResourceAsStream(final ResourceManager caller) throws ResourceLoadingException {
    try {/*w w w .  ja va  2 s . co m*/
        final URLConnection c = url.openConnection();
        c.setDoOutput(false);
        c.setAllowUserInteraction(false);
        c.connect();
        if (isFixBrokenWebServiceDateHeader() == false) {
            readMetaData(c);
        }
        return c.getInputStream();
    } catch (IOException e) {
        throw new ResourceLoadingException("Failed to open URL connection", e);
    }
}

From source file:org.pentaho.reporting.libraries.resourceloader.loader.URLResourceData.java

private void readMetaData() throws IOException {
    if (metaDataOK) {
        if ((System.currentTimeMillis() - lastDateMetaDataRead) < URLResourceData.getFixedCacheDelay()) {
            return;
        }/*from   ww  w  . ja  v a2  s  . c om*/
        if (isFixBrokenWebServiceDateHeader()) {
            return;
        }

    }

    final URLConnection c = url.openConnection();
    c.setDoOutput(false);
    c.setAllowUserInteraction(false);
    if (c instanceof HttpURLConnection) {
        final HttpURLConnection httpURLConnection = (HttpURLConnection) c;
        httpURLConnection.setRequestMethod("HEAD");
    }
    c.connect();
    readMetaData(c);
    c.getInputStream().close();
}

From source file:org.apache.falcon.logging.JobLogMover.java

private InputStream getURLinputStream(URL url) throws IOException {
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    connection.connect();// w w  w.j av  a2 s  .com
    return connection.getInputStream();
}

From source file:eu.europa.ec.markt.dss.validation.tsp.OnlineTSPSource.java

/**
 * Get timestamp token - communications layer
 * //from   w w  w .  j a va  2s. co m
 * @return - byte[] - TSA response, raw bytes (RFC 3161 encoded)
 */
protected byte[] getTSAResponse(byte[] requestBytes) throws IOException {
    // Setup the TSA connection

    URL tspUrl = new URL(tspServer);
    URLConnection tsaConnection = tspUrl.openConnection();

    tsaConnection.setDoInput(true);
    tsaConnection.setDoOutput(true);
    tsaConnection.setUseCaches(false);
    tsaConnection.setRequestProperty("Content-Type", "application/timestamp-query");
    // tsaConnection.setRequestProperty("Content-Transfer-Encoding",
    // "base64");
    tsaConnection.setRequestProperty("Content-Transfer-Encoding", "binary");

    OutputStream out = tsaConnection.getOutputStream();
    out.write(requestBytes);
    out.close();

    // Get TSA response as a byte array
    InputStream inp = tsaConnection.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = inp.read(buffer, 0, buffer.length)) >= 0) {
        baos.write(buffer, 0, bytesRead);
    }
    byte[] respBytes = baos.toByteArray();

    String encoding = tsaConnection.getContentEncoding();
    if (encoding != null && encoding.equalsIgnoreCase("base64")) {
        respBytes = new Base64().decode(respBytes);
    }
    return respBytes;
}

From source file:de.liedtke.data.url.BasicDAOUrl.java

protected JSONObject requestUrl(final String daoName, final String methodName, final String jsonValue)
        throws JSONException {
    String jsonString = null;/*from  www .j  a  v a 2s  .co m*/
    try {
        // Construct data
        final StringBuilder params = new StringBuilder();
        params.append(URLEncoder.encode("daoName", Constants.UTF8));
        params.append("=");
        params.append(URLEncoder.encode(daoName, Constants.UTF8));
        params.append("&");
        params.append(URLEncoder.encode("methodName", Constants.UTF8));
        params.append("=");
        params.append(URLEncoder.encode(methodName, Constants.UTF8));
        if (jsonValue != null) {
            params.append("&");
            params.append(URLEncoder.encode("jsonValue", Constants.UTF8));
            params.append("=");
            params.append(URLEncoder.encode(jsonValue, Constants.UTF8));
        }
        params.append("&");
        params.append(URLEncoder.encode("kind", Constants.UTF8));
        params.append("=");
        params.append(URLEncoder.encode(ResultKind.JSON.toString(), Constants.UTF8));

        // Send data
        URL url = new URL(address);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(params.toString());
        wr.flush();

        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final StringBuilder sBuilder = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sBuilder.append(line);
        }
        jsonString = sBuilder.toString();
        wr.close();
        rd.close();
    } catch (UnsupportedEncodingException e) {
        logger.warning("UnsupportedEncodingException occured: " + e.getMessage());
    } catch (IOException e) {
        logger.warning("IOException occured: " + e.getMessage());
    }
    JSONObject json = null;
    if (jsonString == null) {
        json = null;
    } else {
        json = new JSONObject(jsonString);
    }
    return json;
}

From source file:eu.europa.esig.dss.client.http.NativeHTTPDataLoader.java

@Override
public byte[] post(String url, byte[] content) {
    OutputStream out = null;/*from ww w .  j  a va2s .  c  o  m*/
    InputStream inputStream = null;
    byte[] result = null;
    try {
        URLConnection connection = new URL(url).openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        out = connection.getOutputStream();
        IOUtils.write(content, out);
        inputStream = connection.getInputStream();
        result = IOUtils.toByteArray(inputStream);
    } catch (IOException e) {
        throw new DSSException("An error occured while HTTP POST for url '" + url + "' : " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(inputStream);
    }
    return result;
}

From source file:nl.welteninstituut.tel.oauth.OauthWorker.java

protected String postToURL(URL url, String data) throws IOException {
    try {//from   w ww  . ja va2s .com
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String result = "";
        String line;
        while ((line = rd.readLine()) != null) {
            result += line;
        }
        wr.close();
        rd.close();
        return result;
    } catch (Exception e) {
    }
    return "{}";
}

From source file:dlauncher.dialogs.Login.java

private void login_write(String UserName, String Password) {
    Logger.getGlobal().info("Started login process");
    Logger.getGlobal().info("Writing login data..");
    try {/*from   www . j  ava 2 s .  c  o  m*/
        url = new URL("http://authserver.mojang.com/authenticate");

        final URLConnection con = url.openConnection();
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        con.setDoOutput(true);
        con.setDoInput(true);

        con.setRequestProperty("Content-Type", "application/json");
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()))) {
            writer.write("{\n" + "  \"agent\": {" + "    \"name\": \"Minecraft\"," + "    \"version\": 1" + "\n"
                    + "  },\n" + "  \"username\": \"" + UserName + "\",\n" + "\n" + "  \"password\": \""
                    + Password + "\",\n" + "}");

            writer.close();
        }
        Logger.getGlobal().info("Succesful written login data");
    } catch (MalformedURLException ex) {
        Logger.getGlobal().warning("Failed Writing login data,");
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, "", ex);
    } catch (IOException ex) {
        Logger.getGlobal().warning("Failed Writing login data,");
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, "", ex);
    }
}

From source file:org.motechproject.mobile.omp.manager.intellivr.IntellIVRServerImpl.java

public ResponseType requestCall(RequestType request) {

    AutoCreate ac = new AutoCreate();
    ac.setRequest(request);/*from w ww  .j  av a  2  s . c o  m*/

    ResponseType response = null;

    try {

        Marshaller marshaller = jaxbc.createMarshaller();
        Unmarshaller unmarshaller = jaxbc.createUnmarshaller();

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        marshaller.marshal(ac, byteStream);

        String xml = byteStream.toString();

        URL url = new URL(this.serverURL);
        URLConnection con = url.openConnection();

        con.setDoInput(true);
        con.setDoOutput(true);

        con.setRequestProperty("Content-Type", "text/xml");
        con.setRequestProperty("Content-transfer-encoding", "text");

        OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());

        log.info("Sending request: " + xml);

        out.write(xml);
        out.flush();
        out.close();

        InputStream in = con.getInputStream();

        int len = 4096;
        byte[] buffer = new byte[len];
        int off = 0;
        int read = 0;
        while ((read = in.read(buffer, off, len)) != -1) {
            off += read;
            len -= off;
        }

        String responseText = new String(buffer, 0, off);

        log.debug("Received response: " + responseText);

        Object o = unmarshaller.unmarshal(new ByteArrayInputStream(responseText.getBytes()));

        if (o instanceof AutoCreate) {
            AutoCreate acr = (AutoCreate) o;
            response = acr.getResponse();
        }

    } catch (MalformedURLException e) {
        log.error("", e);
    } catch (IOException e) {
        log.error("", e);
    } catch (JAXBException e) {
        log.error("", e);
    } finally {
        if (response == null) {
            response = new ResponseType();
            response.setStatus(StatusType.ERROR);
            response.setErrorCode(ErrorCodeType.MOTECH_UNKNOWN_ERROR);
            response.setErrorString("Unknown error occurred sending request to IVR server");
        }

    }
    return response;
}