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:org.imsglobal.simplelti.SimpleLTIUtil.java

public static Properties doLaunch(String lti2EndPoint, Properties newMap) {
    M_log.warning("Warning: SimpleLTIUtil using deprecated non-POST launch to -" + lti2EndPoint);
    Properties retProp = new Properties();
    retProp.setProperty("status", "fail");

    String postData = "";
    // Yikes - iterating through properties is nasty
    for (Object okey : newMap.keySet()) {
        if (!(okey instanceof String))
            continue;
        String key = (String) okey;
        if (key == null)
            continue;
        String value = newMap.getProperty(key);
        if (value == null)
            continue;
        if (value.equals(""))
            continue;
        value = encodeFormText(value);// w  ww .ja  v a  2 s.  co m
        if (postData.length() > 0)
            postData = postData + "&";
        postData = postData + encodeFormText(key) + "=" + value;
    }
    if (postData != null)
        retProp.setProperty("_post_data", postData);
    dPrint("LTI2 POST=" + postData);

    String postResponse = null;

    URLConnection urlc = null;
    try {
        // Thanks: http://xml.nig.ac.jp/tutorial/rest/index.html
        URL url = new URL(lti2EndPoint);

        InputStream inp = null;
        // make connection, use post mode, and send query
        urlc = url.openConnection();
        urlc.setDoOutput(true);
        urlc.setAllowUserInteraction(false);
        PrintStream ps = new PrintStream(urlc.getOutputStream());
        ps.print(postData);
        ps.close();
        dPrint("Post Complete");
        inp = urlc.getInputStream();

        // Retrieve result
        BufferedReader br = new BufferedReader(new InputStreamReader(inp));
        String str;
        StringBuffer sb = new StringBuffer();
        while ((str = br.readLine()) != null) {
            sb.append(str);
            sb.append("\n");
        }
        br.close();
        postResponse = sb.toString();

        if (postResponse == null) {
            setErrorMessage(retProp, "Launch REST Web Service returned nothing");
            return retProp;
        }
    } catch (Exception e) {
        // Retrieve error stream if it exists
        if (urlc != null && urlc instanceof HttpURLConnection) {
            try {
                HttpURLConnection urlh = (HttpURLConnection) urlc;
                BufferedReader br = new BufferedReader(new InputStreamReader(urlh.getErrorStream()));
                String str;
                StringBuffer sb = new StringBuffer();
                while ((str = br.readLine()) != null) {
                    sb.append(str);
                    sb.append("\n");
                }
                br.close();
                postResponse = sb.toString();
                dPrint("LTI ERROR response=" + postResponse);
            } catch (Exception f) {
                dPrint("LTI Exception in REST call=" + e);
                // e.printStackTrace();
                setErrorMessage(retProp, "Failed REST service call. Exception=" + e);
                postResponse = null;
                return retProp;
            }
        } else {
            dPrint("LTI General Failure" + e.getMessage());
            // e.printStackTrace();
        }
    }

    if (postResponse != null)
        retProp.setProperty("_post_response", postResponse);
    dPrint("LTI2 Response=" + postResponse);
    // Check to see if we received anything - and then parse it
    Map<String, String> respMap = null;
    if (postResponse == null) {
        setErrorMessage(retProp, "Web Service Returned Nothing");
        return retProp;
    } else {
        if (postResponse.indexOf("<?xml") != 0) {
            int pos = postResponse.indexOf("<launchResponse");
            if (pos > 0) {
                M_log.warning("Warning: Dropping first " + pos
                        + " non-XML characters of response to find <launchResponse");
                postResponse = postResponse.substring(pos);
            }
        }
        respMap = XMLMap.getMap(postResponse);
    }
    if (respMap == null) {
        String errorOut = postResponse;
        if (errorOut.length() > 500) {
            errorOut = postResponse.substring(0, 500);
        }
        M_log.warning("Error Parsing Web Service XML:\n" + errorOut + "\n");
        setErrorMessage(retProp, "Error Parsing Web Service XML");
        return retProp;
    }

    // We will tolerate this one backwards compatibility
    String launchUrl = respMap.get("/launchUrl");
    String launchWidget = null;

    if (launchUrl == null) {
        launchUrl = respMap.get("/launchResponse/launchUrl");
    }

    if (launchUrl == null) {
        launchWidget = respMap.get("/launchResponse/widget");

        /* Remove until we have jTidy 0.8 or later in the repository
        if ( launchWidget != null && launchWidget.length() > 0 ) {
                 M_log.warning("Pre Tidy:\n"+launchWidget);
                 Tidy tidy = new Tidy();
                 tidy.setIndentContent(true);
                 tidy.setSmartIndent(true);
                 tidy.setPrintBodyOnly(true);
                 tidy.setTidyMark(false);
                 // tidy.setQuiet(true);
                 // tidy.setShowWarnings(false);
                 InputStream is = new ByteArrayInputStream(launchWidget.getBytes());
                 OutputStream os = new ByteArrayOutputStream();
                 tidy.parse(is,os);
                 String tidyOutput = os.toString();
                 M_log.warning("Post Tidy:\n"+tidyOutput);
                 if ( tidyOutput != null && tidyOutput.length() > 0 ) launchWidget = os.toString();
              }
        */
    }

    dPrint("launchUrl = " + launchUrl);
    dPrint("launchWidget = " + launchWidget);

    if (launchUrl == null && launchWidget == null) {
        String eMsg = respMap.get("/launchResponse/code") + ":" + respMap.get("/launchResponse/description");
        setErrorMessage(retProp, "Error on Launch:" + eMsg);
        return retProp;
    }

    if (launchUrl != null)
        retProp.setProperty("launchurl", launchUrl);
    if (launchWidget != null)
        retProp.setProperty("launchwidget", launchWidget);
    String postResp = respMap.get("/launchResponse/type");
    if (postResp != null)
        retProp.setProperty("type", postResp);
    retProp.setProperty("status", "success");

    return retProp;
}

From source file:org.apache.camel.component.stream.StreamProducer.java

private OutputStream resolveStreamFromUrl() throws IOException {
    String u = endpoint.getUrl();
    ObjectHelper.notEmpty(u, "url");
    if (LOG.isDebugEnabled()) {
        LOG.debug("About to write to url: " + u);
    }//from w  w w  . j  a v a 2  s.  c  o  m

    URL url = new URL(u);
    URLConnection c = url.openConnection();
    return c.getOutputStream();
}

From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java

/**
 * Connects to the  server, authenticates the provided username and
 * password.// w  ww  .  ja  va 2 s.  c  o m
 * 
 * @param username The user's username
 * @param password The user's password
 * @return String The authentication token returned by the server (or null)
 */
public static String authenticate(String username, String accessKey, String base_url) {
    String token = null;
    String hash = null;
    authenticate_log_text = "authenticate()\n";
    AUTH_URI = base_url + "/webservice.php";
    authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username="
            + username + "\n";

    Log.d(TAG, "AUTH_URI : ");
    Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
    // =========== get challenge token ==============================
    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    try {

        URL url;

        // HTTP GET REQUEST
        url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username);
        HttpURLConnection con;
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-length", "0");
        con.setUseCaches(false);
        // for some site that redirects based on user agent
        con.setInstanceFollowRedirects(true);
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15");
        con.setAllowUserInteraction(false);
        int timeout = 20000;
        con.setConnectTimeout(timeout);
        con.setReadTimeout(timeout);
        con.connect();
        int status = con.getResponseCode();

        authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n";
        switch (status) {
        case 200:
        case 201:
        case 302:
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();
            Log.d(TAG, "message body");
            Log.d(TAG, sb.toString());

            authenticate_log_text = authenticate_log_text + "body : " + sb.toString();
            if (status == 302) {
                authenticate_log_text = sb.toString();
                return null;
            }

            JSONObject result = new JSONObject(sb.toString());
            Log.d(TAG, result.getString("result"));
            JSONObject data = new JSONObject(result.getString("result"));
            token = data.getString("token");
            break;
        case 401:
            Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "Server auth error";
            return null;
        default:
            Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream()));
            authenticate_log_text = authenticate_log_text + "connection status code :" + status;
            return null;
        }

    } catch (ClientProtocolException e) {
        Log.i(TAG, "getchallenge:http protocol error");
        Log.e(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n";
        return null;
    } catch (IOException e) {
        Log.e(TAG, "getchallenge: IO Exception");
        Log.e(TAG, e.getMessage());
        Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username);
        authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n";
        return null;

    } catch (JSONException e) {
        Log.i(TAG, "json exception");
        authenticate_log_text = authenticate_log_text + "JSon exception\n";

        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

    // ================= login ==================

    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(token.getBytes());
        m.update(accessKey.getBytes());
        hash = new BigInteger(1, m.digest()).toString(16);
        Log.i(TAG, "hash");
        Log.i(TAG, hash);
    } catch (NoSuchAlgorithmException e) {
        authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n";
        e.printStackTrace();
    }

    try {
        String charset;
        charset = "utf-8";
        String query = String.format("operation=login&username=%s&accessKey=%s",
                URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset));
        authenticate_log_text = authenticate_log_text + "login()\n";
        URLConnection connection = new URL(AUTH_URI).openConnection();
        connection.setDoOutput(true); // Triggers POST.
        int timeout = 20000;
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setAllowUserInteraction(false);
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
        connection.setUseCaches(false);

        OutputStream output = connection.getOutputStream();
        try {
            output.write(query.getBytes(charset));
        } finally {
            try {
                output.close();
            } catch (IOException logOrIgnore) {

            }
        }
        Log.d(TAG, "Query written");
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        Log.d(TAG, "message post body");
        Log.d(TAG, sb.toString());
        authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n";
        JSONObject result = new JSONObject(sb.toString());

        String success = result.getString("success");
        Log.i(TAG, success);

        if (success == "true") {
            Log.i(TAG, result.getString("result"));
            Log.i(TAG, "sucesssfully logged  in is");
            JSONObject data = new JSONObject(result.getString("result"));
            sessionName = data.getString("sessionName");

            Log.i(TAG, sessionName);
            authenticate_log_text = authenticate_log_text + "successfully logged in\n";
            return token;
        } else {
            // success is false, retrieve error
            JSONObject data = new JSONObject(result.getString("error"));
            authenticate_log_text = "can not login :\n" + data.toString();

            return null;
        }
        //token = data.getString("token");
        //Log.i(TAG,token);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "login: http protocol error");
        Log.d(TAG, e.getMessage());
        authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";
    } catch (IOException e) {
        Log.d(TAG, "login: IO Exception");
        Log.d(TAG, e.getMessage());

        authenticate_log_text = authenticate_log_text + "login: IO Exception \n";
        authenticate_log_text = authenticate_log_text + e.getMessage() + "\n";

    } catch (JSONException e) {
        Log.d(TAG, "JSON exception");
        // TODO Auto-generated catch block
        authenticate_log_text = authenticate_log_text + "JSON exception ";
        authenticate_log_text = authenticate_log_text + e.getMessage();
        e.printStackTrace();
    }
    return null;
    // ========================================================================

}

From source file:com.simplenoteapp.test.Test.java

/**
 * Base 64 encode the given data and post it to uri.
 * @param uri to which the data is to be posted
 * @param postData string to be converted to UTF-8, then encoded
 * as base 64 and posted to uri// w  w w.j  a  va  2s .c om
 * @return content returned from the request
 * @throws IOException
 */
public String postBase64(String uriString, String postData) throws IOException {
    Test.log("postBase64 uri=" + uriString + " data=" + postData);
    byte[] base64 = Base64.encodeBase64(postData.getBytes(), false, false);
    Test.log("base64=" + new String(base64));

    URL url = new URL(uriString);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStream out = conn.getOutputStream();
    out.write(base64);
    out.flush();
    String response = readResponse(conn.getInputStream());
    out.close();
    return response;
}

From source file:com.github.beat.signer.pdf_signer.TSAClient.java

private void sendRequest(byte[] request, URLConnection connection) throws IOException {
    OutputStream output = null;//from w  ww .  ja  v  a2s  .c o  m
    try {
        output = connection.getOutputStream();
        output.write(request);
    } finally {
        IOUtils.closeQuietly(output);
    }
}

From source file:key.access.manager.HttpHandler.java

public String connect(String url, ArrayList data) throws IOException {
    try {//ww w  . j a v  a2  s.c  om
        // open a connection to the site
        URL connectionUrl = new URL(url);
        URLConnection con = connectionUrl.openConnection();
        // activate the output
        con.setDoOutput(true);
        PrintStream ps = new PrintStream(con.getOutputStream());
        // send your parameters to your site
        for (int i = 0; i < data.size(); i++) {
            ps.print(data.get(i));
            //System.out.println(data.get(i));
            if (i != data.size() - 1) {
                ps.print("&");
            }
        }

        // we have to get the input stream in order to actually send the request
        InputStream inStream = con.getInputStream();
        Scanner s = new Scanner(inStream).useDelimiter("\\A");
        String result = s.hasNext() ? s.next() : "";
        System.out.println(result);

        // close the print stream
        ps.close();
        return result;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return "error";
    } catch (IOException e) {
        e.printStackTrace();
        return "error";
    }
}

From source file:org.apache.servicemix.http.HttpAddressingTest.java

public void testOkFromUrl() throws Exception {
    URLConnection connection = new URL("http://localhost:8192/Service/").openConnection();
    connection.setDoOutput(true);/*from   www. j a  va2s .  c o  m*/
    connection.setDoInput(true);
    OutputStream os = connection.getOutputStream();
    // Post the request file.
    InputStream fis = getClass().getResourceAsStream("addressing-request.xml");
    FileUtil.copyInputStream(fis, os);
    // Read the response.
    InputStream is = connection.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileUtil.copyInputStream(is, baos);
    log.info(baos.toString());
}

From source file:tkwatch.Utilities.java

/**
 * Issues a TradeKing API request. Adapted from the <i>TradeKing API
 * Reference Guide</i>, 03.25.2011, p. 51.
 * //from  w  w w .j a  v a 2  s.  c o  m
 * @param resourceUrl
 *            The URL to which API requests must be made.
 * @param body
 *            The body of the API request.
 * @param appKey
 *            The user's application key.
 * @param userKey
 *            The user's key.
 * @param userSecret
 *            The user's secret key.
 * @return Returns the result of the API request.
 */
public static final String tradeKingRequest(final String resourceUrl, final String body, final String appKey,
        final String userKey, final String userSecret) {
    String response = new String();
    try {
        String timestamp = String.valueOf(Calendar.getInstance().getTimeInMillis());
        String request_data = body + timestamp;
        String signature = generateSignature(request_data, userSecret);
        URL url = new URL(resourceUrl);
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/xml");
        conn.setRequestProperty("Accept", "application/xml");
        conn.setRequestProperty("TKI_TIMESTAMP", timestamp);
        conn.setRequestProperty("TKI_SIGNATURE", signature);
        conn.setRequestProperty("TKI_USERKEY", userKey);
        conn.setRequestProperty("TKI_APPKEY", appKey);
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(body);
        out.flush();
        out.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String temp;
        while ((temp = in.readLine()) != null) {
            response += temp + "\n";
        }
        in.close();
        return response;
    } catch (java.security.SignatureException e) {
        errorMessage(e.getMessage());
        return "";
    } catch (java.io.IOException e) {
        errorMessage(e.getMessage());
        return "";
    }
}

From source file:org.intermine.bio.web.logic.LiftOverService.java

/**
 * Send a HTTP POST request to liftOver service.
 *
 * @param grsc the Genomic Region Search constraint
 * @param org human or mouse//from  www  .j a v a2 s  . c  o m
 * @param genomeVersionSource older genome version
 * @param genomeVersionTarget intermine genome version
 * @param liftOverServerURL url
 * @return a list of GenomicRegion
 */
public String doLiftOver(GenomicRegionSearchConstraint grsc, String org, String genomeVersionSource,
        String genomeVersionTarget, String liftOverServerURL) {

    List<GenomicRegion> genomicRegionList = grsc.getGenomicRegionList();
    String liftOverResponse;

    String coords = converToBED(genomicRegionList);
    String organism = ORGANISM_COMMON_NAME_MAP.get(org);

    try {
        // Construct data
        String data = URLEncoder.encode("coords", "UTF-8") + "=" + URLEncoder.encode(coords, "UTF-8");
        data += "&" + URLEncoder.encode("source", "UTF-8") + "="
                + URLEncoder.encode(genomeVersionSource, "UTF-8");
        data += "&" + URLEncoder.encode("target", "UTF-8") + "="
                + URLEncoder.encode(genomeVersionTarget, "UTF-8");

        // Send data
        URL url;
        // liftOverServerURL ends with "/"
        if (!liftOverServerURL.endsWith("/")) {
            url = new URL(liftOverServerURL + "/" + organism);
        } else {
            url = new URL(liftOverServerURL + organism);
        }
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        wr.close();

        liftOverResponse = new String(IOUtils.toCharArray(conn.getInputStream()));

        LOG.info("LiftOver response message: \n" + liftOverResponse);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return liftOverResponse;
}

From source file:oneDrive.OneDriveAPI.java

public static void uploadFile(String filePath) {
    URLConnection urlconnection = null;
    try {/*w w  w  .j  a  va  2s  .com*/
        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();
    }

}