Example usage for java.net URLConnection getOutputStream

List of usage examples for java.net URLConnection getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:net.sf.joost.trax.TrAXHelper.java

/**
 * HelperMethod for initiating StxEmitter.
 * @param result A <code>Result</code> object.
 * @return An <code>StxEmitter</code>.
 * @throws javax.xml.transform.TransformerException
 *//*from  w  ww .j a v a  2 s.c  om*/
public static StxEmitter initStxEmitter(Result result, Processor processor, Properties outputProperties)
        throws TransformerException {

    if (outputProperties == null)
        outputProperties = processor.outputProperties;

    if (DEBUG)
        log.debug("init StxEmitter");
    // Return the content handler for this Result object
    try {
        // Result object could be SAXResult, DOMResult, or StreamResult
        if (result instanceof SAXResult) {
            final SAXResult target = (SAXResult) result;
            final ContentHandler handler = target.getHandler();
            if (handler != null) {
                if (DEBUG)
                    log.debug("return SAX specific Implementation for " + "StxEmitter");
                //SAX specific Implementation
                return new SAXEmitter(handler);
            }
        } else if (result instanceof DOMResult) {
            if (DEBUG)
                log.debug("return DOM specific Implementation for " + "StxEmitter");
            //DOM specific Implementation
            return new DOMEmitter((DOMResult) result);
        } else if (result instanceof StreamResult) {
            if (DEBUG)
                log.debug("return StreamResult specific Implementation " + "for StxEmitter");
            // Get StreamResult
            final StreamResult target = (StreamResult) result;
            // StreamResult may have been created with a java.io.File,
            // java.io.Writer, java.io.OutputStream or just a String
            // systemId.
            // try to get a Writer from Result object
            final Writer writer = target.getWriter();
            if (writer != null) {
                if (DEBUG)
                    log.debug("get a Writer object from Result object");
                return StreamEmitter.newEmitter(writer, DEFAULT_ENCODING, outputProperties);
            }
            // or try to get an OutputStream from Result object
            final OutputStream ostream = target.getOutputStream();
            if (ostream != null) {
                if (DEBUG)
                    log.debug("get an OutputStream from Result object");
                return StreamEmitter.newEmitter(ostream, outputProperties);
            }
            // or try to get just a systemId string from Result object
            String systemId = result.getSystemId();
            if (DEBUG)
                log.debug("get a systemId string from Result object");
            if (systemId == null) {
                if (DEBUG)
                    log.debug("JAXP_NO_RESULT_ERR");
                throw new TransformerException("JAXP_NO_RESULT_ERR");
            }
            // System Id may be in one of several forms, (1) a uri
            // that starts with 'file:', (2) uri that starts with 'http:'
            // or (3) just a filename on the local system.
            OutputStream os = null;
            URL url = null;
            if (systemId.startsWith("file:")) {
                url = new URL(systemId);
                os = new FileOutputStream(url.getFile());
                return StreamEmitter.newEmitter(os, outputProperties);
            } else if (systemId.startsWith("http:")) {
                url = new URL(systemId);
                URLConnection connection = url.openConnection();
                os = connection.getOutputStream();
                return StreamEmitter.newEmitter(os, outputProperties);
            } else {
                // system id is just a filename
                File tmp = new File(systemId);
                url = tmp.toURL();
                os = new FileOutputStream(url.getFile());
                return StreamEmitter.newEmitter(os, outputProperties);
            }
        }
        // If we cannot create the file specified by the SystemId
    } catch (IOException iE) {
        if (DEBUG)
            log.debug(iE);
        throw new TransformerException(iE);
    } catch (ParserConfigurationException pE) {
        if (DEBUG)
            log.debug(pE);
        throw new TransformerException(pE);
    }
    return null;
}

From source file:Main.java

/**
 *  This method is used to send a XML request file to web server to process the request and return
 *  xml response containing event id./*from w  w  w. j  a  v a  2 s  .co m*/
 */
public static String postXMLWithTimeout(String postUrl, String xml, int readTimeout) throws Exception {

    System.out.println("XMLUtils.postXMLWithTimeout: Connecting to Web Server .......");

    InputStream in = null;
    BufferedReader bufferedReader = null;
    OutputStream out = null;
    PrintWriter printWriter = null;
    StringBuffer responseMessageBuffer = new StringBuffer("");

    try {
        URL url = new URL(postUrl);
        URLConnection con = url.openConnection();

        // Prepare for both input and output
        con.setDoInput(true);
        con.setDoOutput(true);

        // Turn off caching
        con.setUseCaches(false);
        con.setRequestProperty("Content-Type", "text/xml");
        con.setReadTimeout(readTimeout);
        out = con.getOutputStream();
        // Write the arguments as post data
        printWriter = new PrintWriter(out);

        printWriter.println(xml);
        printWriter.flush();

        //Process response and return back to caller function
        in = con.getInputStream();
        bufferedReader = new BufferedReader(new InputStreamReader(in));
        String tempStr = null;

        int tempClearResponseMessageBufferCounter = 0;
        while ((tempStr = bufferedReader.readLine()) != null) {
            tempClearResponseMessageBufferCounter++;
            //clear the buffer for the first time
            if (tempClearResponseMessageBufferCounter == 1)
                responseMessageBuffer.setLength(0);
            responseMessageBuffer.append(tempStr);
        }

    } catch (Exception ex) {
        throw ex;
    } finally {
        System.out.println("Calling finally in POSTXML");
        try {
            if (in != null)
                in.close();
        } catch (Exception eex) {
            System.out.println("COULD NOT Close Input Stream in try");
        }
        try {
            if (out != null)
                out.close();
        } catch (Exception eex) {
            System.out.println("COULD NOT Close Output Stream in try");
        }

    }
    System.out.println("XMLUtils.postXMLWithTimeout: end .......");
    return responseMessageBuffer.toString();
}

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

protected static String post(URL url, String payload, Map props) throws IOException {
    String propstr = new String();

    for (Iterator i = props.keySet().iterator(); i.hasNext();) {
        String key = (String) i.next();
        propstr = propstr + URLEncoder.encode(key, "UTF-8") + "="
                + URLEncoder.encode((String) props.get(key), "UTF-8");
        if (i.hasNext()) {
            propstr = propstr + "&";
        }/* ww w  . ja  va  2s .c o m*/
    }

    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream());
    osr.write(propstr);
    osr.flush();

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

    return resp;
}

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

protected static String post(URL url, Map props) throws IOException {
    String propstr = new String();

    for (Iterator i = props.keySet().iterator(); i.hasNext();) {
        String key = (String) i.next();
        propstr = propstr + URLEncoder.encode(key, "UTF-8") + "="
                + URLEncoder.encode((String) props.get(key), "UTF-8");
        if (i.hasNext()) {
            propstr = propstr + "&";
        }//from w  w w  .  j  a  va2  s.c  o  m
    }

    SSLUtils.verifyHost();

    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream());
    osr.write(propstr);
    osr.flush();

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

    return resp;
}

From source file:org.wso2.carbon.connector.integration.test.util.ConnectorIntegrationUtil.java

public static OMElement sendXMLRequest(String addUrl, String query)
        throws MalformedURLException, IOException, XMLStreamException {
    String charset = "UTF-8";
    System.out.println("=======url======" + addUrl + "=======" + query);
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);/*from  w w  w  . j  a  v  a  2  s. c o m*/
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "text/xml;charset=" + charset);
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException logOrIgnore) {
                log.error("Error while closing the connection");
            }
        }
    }

    HttpURLConnection httpConn = (HttpURLConnection) connection;
    InputStream response;

    if (httpConn.getResponseCode() >= 400) {
        response = httpConn.getErrorStream();
    } else {
        response = connection.getInputStream();
    }

    String out = "{}";
    if (response != null) {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = response.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }

        if (!sb.toString().trim().isEmpty()) {
            out = sb.toString();
        }
    }
    System.out.println("=======out======" + out);
    OMElement omElement = AXIOMUtil.stringToOM(out);
    return omElement;
}

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

/**
 * @param url/*  w ww  .  j  a v a  2  s.  c om*/
 * @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:de.akquinet.android.androlog.reporter.PostReporter.java

/**
 * Executes the given request as a HTTP POST action.
 *
 * @param url//w ww.j  a  v a  2  s .co  m
 *            the url
 * @param params
 *            the parameter
 * @return the response as a String.
 * @throws IOException
 *             if the server cannot be reached
 */
public static void post(URL url, String params) throws IOException {
    URLConnection conn = url.openConnection();
    if (conn instanceof HttpURLConnection) {
        ((HttpURLConnection) conn).setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
    }
    OutputStreamWriter writer = null;
    try {
        conn.setDoOutput(true);
        writer = new OutputStreamWriter(conn.getOutputStream(), Charset.forName("UTF-8"));
        // write parameters
        writer.write(params);
        writer.flush();
    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:org.omegat.languagetools.LanguageToolNetworkBridge.java

/**
 * Try to talk with LT server and return result
 *//*www .j  ava  2 s .c om*/
static boolean testServer(String testUrl) {
    if (testUrl.trim().toLowerCase(Locale.ENGLISH).startsWith("https://languagetool.org/api/v2/check")) {
        // Blacklist the official LanguageTool public API specifically
        // because this is what users are most likely to try, but they ask
        // not to send automated requests:
        // http://wiki.languagetool.org/public-http-api
        return false;
    }
    try {
        URL url = new URL(testUrl);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        try (OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream())) {
            // Supply a dummy disabled category to force the server to take
            // its configuration from this query only, not any server-side
            // config.
            writer.write(buildPostData(null, "en-US", null, "Test", "FOO", null, null));
            writer.flush();
        }
        checkHttpError(conn);
        try (InputStream in = conn.getInputStream()) {
            String response = IOUtils.toString(in, StandardCharsets.UTF_8);
            if (response.contains("<?xml")) {
                Log.logErrorRB("LT_WRONG_FORMAT_RESPONSE");
                return false;
            } else {
                return true;
            }
        }
    } catch (Exception e) {
        Log.log(e);
        return false;
    }
}

From source file:com.example.cmput301.model.WebService.java

/**
 * Sets up http connection to the web server and returns the connection.
 * @param conn URLConnection/*from   www .  j  a v a2s  .  co m*/
 * @param data string to send to web service.
 * @return String response from web service.
 * @throws IOException
 */
private static String getHttpResponse(URLConnection conn, String data) throws IOException {
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();
    wr.close();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line, httpResponse = "";
    while ((line = rd.readLine()) != null) {
        // Process line...
        httpResponse += line;
    }
    rd.close();
    return httpResponse;
}

From source file:com.fluidops.iwb.provider.GoogleRefineProvider.java

/**
 * utility to simplify doing POST requests
 * //from  w w  w  .  j  a v a2  s  .com
 * @param url         URL to post to
 * @param parameter      map of parameters to post
 * @return            URLConnection is a state where post parameters have been sent
 * @throws IOException
 * 
 * TODO: move to util class
 */
public static URLConnection doPost(URL url, Map<String, String> parameter) throws IOException {
    URLConnection con = url.openConnection();
    con.setDoOutput(true);

    StringBuilder params = new StringBuilder();
    for (Entry<String, String> entry : parameter.entrySet())
        params.append(StringUtil.urlEncode(entry.getKey())).append("=")
                .append(StringUtil.urlEncode(entry.getValue())).append("&");

    // Send data
    OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
    wr.write(params.toString());
    wr.flush();
    wr.close();

    return con;
}