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: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);
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", "text/xml;charset=" + charset);
    OutputStream output = null;//from  w ww.  j a  va  2s.  c  o  m
    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: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.//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:de.anycook.social.facebook.FacebookHandler.java

@SuppressWarnings("unchecked")
public static String publishtoWall(long facebookID, String accessToken, String message, String header)
        throws IOException {
    StringBuilder out = new StringBuilder();
    StringBuilder data = new StringBuilder();
    data.append("access_token=").append(URLEncoder.encode(accessToken, "UTF-8"));
    data.append("&message=").append(URLEncoder.encode(message, "UTF-8"));
    data.append("&name=").append(URLEncoder.encode(header, "UTF-8"));

    URL url = new URL("https://api.facebook.com/" + facebookID + "/feed");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    try (OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) {
        wr.write(data.toString());/*w  ww  .j a  v a2s  .c  o m*/
        wr.flush();

        try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = rd.readLine()) != null) {
                out.append(line);
            }
        }
    }

    return out.toString();
}

From source file:org.exoplatform.portal.webui.application.GadgetUtil.java

/**
 * Fetchs Metatada of gadget application, create the connection to shindig
 * server to get the metadata TODO cache the informations for better
 * performance//from w ww.j a va 2 s  .c  o  m
 * 
 * @return the string represents metadata of gadget application
 */
public static String fetchGagdetMetadata(String urlStr) {
    String result = null;

    ExoContainer container = ExoContainerContext.getCurrentContainer();
    GadgetRegistryService gadgetService = (GadgetRegistryService) container
            .getComponentInstanceOfType(GadgetRegistryService.class);
    try {
        String data = "{\"context\":{\"country\":\"" + gadgetService.getCountry() + "\",\"language\":\""
                + gadgetService.getLanguage() + "\"},\"gadgets\":[" + "{\"moduleId\":"
                + gadgetService.getModuleId() + ",\"url\":\"" + urlStr + "\",\"prefs\":[]}]}";
        // Send data
        String gadgetServer = getGadgetServerUrl();
        URL url = new URL(gadgetServer + (gadgetServer.endsWith("/") ? "" : "/") + "metadata");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        // Get the response
        result = IOUtils.toString(conn.getInputStream(), "UTF-8");
        wr.close();
    } catch (IOException ioexc) {
        ioexc.printStackTrace();
        return "{}";
    }
    return result;
}

From source file:org.geoserver.security.password.URLMasterPasswordProvider.java

static OutputStream output(URL url, File configDir) throws IOException {
    //check for file url
    if ("file".equalsIgnoreCase(url.getProtocol())) {
        File f = DataUtilities.urlToFile(url);
        if (!f.isAbsolute()) {
            //make relative to config dir
            f = new File(configDir, f.getPath());
        }//w w  w  . jav  a  2  s .  c o  m
        return new FileOutputStream(f);
    } else {
        URLConnection cx = url.openConnection();
        cx.setDoOutput(true);
        return cx.getOutputStream();
    }
}

From source file:org.apache.ambari.view.weather.CityResourceProvider.java

private static InputStream readFrom(String spec) throws IOException {
    URLConnection connection = new URL(spec).openConnection();

    connection.setConnectTimeout(5000);/*from  w w w.  j  a va  2  s.  c om*/
    connection.setDoOutput(true);
    return connection.getInputStream();
}

From source file:org.identityconnectors.office365.jsontoken.JWTTokenHelper.java

/**
 * Get an access token from ACS (STS)./*from ww w.  j  a  va2  s.co  m*/
 * @param stsUrl ACS STS Url.
 * @param assertion Assertion Token.
 * @param resource ExpiresIn name.
 * @return The OAuth access token.
 * @throws SampleAppException If the operation can not be completed successfully.
 */
public static String getOAuthAccessTokenFromACS(String stsUrl, String assertion, String resource)
        throws Exception {

    String accessToken = "";

    URL url = null;

    String data = null;

    data = URLEncoder.encode(JWTTokenHelper.claimTypeGrantType, "UTF-8") + "="
            + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8");
    data += "&" + URLEncoder.encode(JWTTokenHelper.claimTypeAssertion, "UTF-8") + "="
            + URLEncoder.encode(assertion, "UTF-8");
    data += "&" + URLEncoder.encode(JWTTokenHelper.claimTypeResource, "UTF-8") + "="
            + URLEncoder.encode(resource, "UTF-8");

    url = new URL(stsUrl);

    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 line, response = "";

    while ((line = rd.readLine()) != null) {
        response += line;
    }

    wr.close();
    rd.close();

    accessToken = (new JSONObject(response)).optString("access_token");
    return String.format("%s%s", JWTTokenHelper.bearerTokenPrefix, accessToken);
}

From source file:sh.isaac.provider.sync.git.gitblit.utils.ConnectionUtils.java

/**
 * Open connection.//from www.ja  v a2 s.c o m
 *
 * @param url the url
 * @param username the username
 * @param password the password
 * @return the URL connection
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static URLConnection openConnection(String url, String username, char[] password) throws IOException {
    final URL urlObject = new URL(url);
    final URLConnection conn = urlObject.openConnection();

    setAuthorization(conn, username, password);
    conn.setUseCaches(false);
    conn.setDoOutput(true);
    return conn;
}

From source file:com.meetingninja.csse.database.BaseDatabaseAdapter.java

protected static void addRequestHeader(URLConnection connection, boolean isPost) {
    connection.setRequestProperty("User-Agent", USER_AGENT);
    connection.setRequestProperty("Accept", ACCEPT_TYPE);
    connection.setDoOutput(isPost);
    if (isPost) {
        connection.setRequestProperty("Content-Type", CONTENT_TYPE);
    }/*w ww.  j a va2  s.  c o m*/
}

From source file:it.geosolutions.geostore.core.security.password.URLMasterPasswordProvider.java

/**
 * Writes the master password in the file
 * @param url/* w w  w  .  j  a  va2  s .  com*/
 * @param configDir
 * @return
 * @throws IOException
 */
static OutputStream output(URL url, File configDir) throws IOException {
    //check for file URL
    if ("file".equalsIgnoreCase(url.getProtocol())) {
        File f;
        try {
            f = new File(url.toURI());
        } catch (URISyntaxException e) {
            f = new File(url.getPath());
        }
        if (!f.isAbsolute()) {
            //make relative to config dir
            f = new File(configDir, f.getPath());
        }
        return new FileOutputStream(f);
    } else {
        URLConnection cx = url.openConnection();
        cx.setDoOutput(true);
        return cx.getOutputStream();
    }
}